The function foo
below returns a string 'foo'
. How can I get the value 'foo'
which is returned from the thread’s target?
JavaScript
x
10
10
1
from threading import Thread
2
3
def foo(bar):
4
print('hello {}'.format(bar))
5
return 'foo'
6
7
thread = Thread(target=foo, args=('world!',))
8
thread.start()
9
return_value = thread.join()
10
The “one obvious way to do it”, shown above, doesn’t work: thread.join()
returned None
.
Advertisement
Answer
In Python 3.2+, stdlib concurrent.futures
module provides a higher level API to threading
, including passing return values or exceptions from a worker thread back to the main thread:
JavaScript
1
11
11
1
import concurrent.futures
2
3
def foo(bar):
4
print('hello {}'.format(bar))
5
return 'foo'
6
7
with concurrent.futures.ThreadPoolExecutor() as executor:
8
future = executor.submit(foo, 'world!')
9
return_value = future.result()
10
print(return_value)
11