The function foo
below returns a string 'foo'
. How can I get the value 'foo'
which is returned from the thread's target?
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()
The "one obvious way to do it", shown above, doesn't work: thread.join()
returned None
.
Best Answer
One way I've seen is to pass a mutable object, such as a list or a dictionary, to the thread's constructor, along with a an index or other identifier of some sort. The thread can then store its results in its dedicated slot in that object. For example:
If you really want
join()
to return the return value of the called function, you can do this with aThread
subclass like the following:That gets a little hairy because of some name mangling, and it accesses "private" data structures that are specific to
Thread
implementation... but it works.For Python 3: