白猪掌柜的
我看到的一种方法是将可变对象(如List或字典)传递给线程的构造函数,以及某种类型的索引或其他标识符。然后,线程可以将其结果存储在该对象的专用槽中。例如:def foo(bar, result, index):
print 'hello {0}'.format(bar)
result[index] = "foo"from threading import Threadthreads = [None] * 10results = [None] * 10for i in range(len(threads)):
threads[i] = Thread(target=foo, args=('world!', results, i))
threads[i].start()# do some other stufffor i in range(len(threads)):
threads[i].join()print " ".join(results) # what sound does a metasyntactic locomotive make?如果你真的想join()若要返回被调用函数的返回值,可以使用Thread子类如下所示:from threading import Threaddef foo(bar):
print 'hello {0}'.format(bar)
return "foo"class ThreadWithReturnValue(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, Verbose=None):
Thread.__init__(self, group, target, name, args, kwargs, Verbose)
self._return = None
def run(self):
if self._Thread__target is not None:
self._return = self._Thread__target(*self._Thread__args,
**self._Thread__kwargs)
def join(self):
Thread.join(self)
return self._return
twrv = ThreadWithReturnValue(target=foo, args=('world!',))twrv.start()print twrv.join() # prints foo因为某些名称损坏,所以会变得有些毛茸茸的,并且它访问特定于以下的“私有”数据结构。Thread执行.。但很管用。用于丙酮3class ThreadWithReturnValue(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, Verbose=None):
Thread.__init__(self, group, target, name, args, kwargs)
self._return = None
def run(self):
print(type(self._target))
if self._target is not None:
self._return = self._target(*self._args,
**self._kwargs)
def join(self, *args):
Thread.join(self, *args)
return self._return