函数foo
下面返回一个字符串'foo'
..。如何获取该值'foo'
线程的目标返回的是什么?
from threading import Thread
def foo(bar):
print('hello {}'.format(bar))
return 'foo'
thread = Thread(target=foo, args=('world!',))
thread.start()
return_value = thread.join()
上面所示的“一种显而易见的方法”不起作用:thread.join()
返回None
..。
发布于 2019-11-13 11:18:27
在Python 3.2+中,stdlibconcurrent.futures
模块提供了更高级别的API,以threading
,包括将返回值或异常从工作线程传递回主线程:
import concurrent.futures
def foo(bar):
print('hello {}'.format(bar))
return 'foo'
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(foo, 'world!')
return_value = future.result()
print(return_value)
发布于 2011-08-01 11:34:36
我见过的一种方法是将一个可变对象与索引或其他标识符一起传递给线程的构造函数。然后,线程可以将其结果存储在该对象的专用槽中。例如:
def foo(bar, result, index):
print 'hello {0}'.format(bar)
result[index] = "foo"
from threading import Thread
threads = [None] * 10
results = [None] * 10
for i in range(len(threads)):
threads[i] = Thread(target=foo, args=('world!', results, i))
threads[i].start()
# do some other stuff
for i in range(len(threads)):
threads[i].join()
print " ".join(results) # what sound does a metasyntactic locomotive make?
如果你真的想join()
若要返回被调用函数的返回值,可以使用Thread
如下所示的子类:
from threading import Thread
def 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
实现...但它是有效的。
对于python3
class 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
发布于 2013-01-13 07:22:01
FWIW,multiprocessing
模块为此提供了一个很好的接口,该接口使用Pool
类。如果您想继续使用线程而不是进程,可以只使用multiprocessing.pool.ThreadPool
类作为临时替换类。
def foo(bar, baz):
print 'hello {0}'.format(bar)
return 'foo' + baz
from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)
async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo
# do some other stuff in the main process
return_val = async_result.get() # get the return value from your function.
https://stackoverflow.com/questions/6893968
复制相似问题