如何从python中的线程获得返回值?功能foo下面返回一个字符串'foo'..我怎样才能得到价值'foo'哪个是从线程的目标返回的?from threading import Threaddef foo(bar):
print('hello {}'.format(bar))
return 'foo'thread = Thread(target=foo, args=('world!',))thread.start()return_value = thread.join()上面所示的“一种显而易见的方法”是行不通的:thread.join()退回来None.
3 回答
白猪掌柜的
TA贡献1893条经验 获得超10个赞
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
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
添加回答
举报
0/150
提交
取消