Python 多个线程具有相同的协程?
我可以运行多个线程来运行同一个协程的相同副本吗 例如,如果我将线程函数从这个改为Python 多个线程具有相同的协程?,python,multithreading,coroutine,Python,Multithreading,Coroutine,我可以运行多个线程来运行同一个协程的相同副本吗 例如,如果我将线程函数从这个改为 这真的有效吗?如何验证它是否正常工作?我想我已经修复了它,我需要将函数更改为类似这样的函数才能正常工作 @coroutine def _threaded(self, count, target_func): """ Given a target coroutine, spawn $count threads to run copies of them. In order to properl
这真的有效吗?如何验证它是否正常工作?我想我已经修复了它,我需要将函数更改为类似这样的函数才能正常工作
@coroutine
def _threaded(self, count, target_func):
"""
Given a target coroutine, spawn $count threads to run copies of them. In
order to properly use this, do not call the coroutine before calling this,
e.g.
@coroutine
def foo(self):
...
def bar(self):
...
self._threaded(10, self.foo) # <- do not call self.foo,
# just the reference
@param count The number of threads to spawn
@param target_func The reference to the target coroutine
@returns The subnet mask
"""
result = None
messages = Queue()
def default_target_run(index):
target = target_func()
while True:
item = messages.get()
if item is GeneratorExit:
target.close()
return
else:
target.send({'index': index, 'item': item})
# ensure code is testable
target_run = default_target_run
try:
target_run = self._threaded.target_run
except AttributeError:
pass
result = ThreadPool(count).map_async(target_run, range(count))
try:
while True:
item = (yield)
messages.put(item)
except GeneratorExit:
# allow all threads to quit
# by making sure all of them receives the exit message
for i in xrange(count):
messages.put(GeneratorExit)
result.ready()
@coroutine
定义线程(自、计数、目标函数):
"""
给定一个目标协同程序,生成$count线程来运行它们的副本
为了正确使用此功能,请在调用此功能之前不要调用协同程序,
例如
@协同程序
def foo(self):
...
def bar(自):
...
self.\u螺纹(10,self.foo)#
@coroutine
def _threaded(self, count, target_func):
"""
Given a target coroutine, spawn $count threads to run copies of them. In
order to properly use this, do not call the coroutine before calling this,
e.g.
@coroutine
def foo(self):
...
def bar(self):
...
self._threaded(10, self.foo) # <- do not call self.foo,
# just the reference
@param count The number of threads to spawn
@param target_func The reference to the target coroutine
@returns The subnet mask
"""
result = None
messages = Queue()
def default_target_run(index):
target = target_func()
while True:
item = messages.get()
if item is GeneratorExit:
target.close()
return
else:
target.send({'index': index, 'item': item})
# ensure code is testable
target_run = default_target_run
try:
target_run = self._threaded.target_run
except AttributeError:
pass
result = ThreadPool(count).map_async(target_run, range(count))
try:
while True:
item = (yield)
messages.put(item)
except GeneratorExit:
# allow all threads to quit
# by making sure all of them receives the exit message
for i in xrange(count):
messages.put(GeneratorExit)
result.ready()