Sometimes, we want to get the return value from a thread in Python.
In this article, we’ll look at how to get the return value from a thread in Python.
How to get the return value from a thread in Python?
To get the return value from a thread in Python, we can call apply_async
and get
.
For instance, we write
def foo(bar, baz):
return 'foo' + baz
from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)
async_result = pool.apply_async(foo, ('world', 'foo'))
# do some other stuff in the main process
return_val = async_result.get()
to create a thread pool with
pool = ThreadPool(processes=1)
then we create a thread that runs foo
with
async_result = pool.apply_async(foo, ('world', 'foo'))
('world', 'foo')
are the args for foo
.
And then we call async_result.get
to return the value returned from foo
.
Conclusion
To get the return value from a thread in Python, we can call apply_async
and get
.