How to get the return value from a thread?
Need a thread's return value sans the complicated dance? Use concurrent.futures.ThreadPoolExecutor
:
executor.submit()
kickstarts the function. future.result()
waits patiently for completion, holding the results once done.
Thread-return techniques
For the thread warriors, a cache of tools to retrieve thread return values:
Thread-safe Queues
Queues can act as a communication bridge between threads. Have the worker store the return value in the queue, then just sit back and pick up the results.
Custom join with Thread subclasses
How about the ninja technique? Subclass Thread
, customize the join()
method, and boom—you've got the thread return value.
Async to the rescue
The multiprocessing.pool.ThreadPool
method comes with apply_async
for a non-blocking execution. Fetch the values later, just like getting your online shopping delivery!
Asyncio kingdom
Working with asyncio
? Get your concurrent.futures
with a little dressing of asyncio.Future
. Now they are on a par with asyncio
coroutines.
Using modern Python for thread returns
Wield the tools of Python 3 to your benefit. They provide a more efficient and intuitive means to handle thread results.
Rejoice with concurrent.futures (Python 3.2+)
No need for handling each thread with care. With ThreadPoolExecutor
from concurrent.futures
, wrangling thread results is just a walk in the park.
Lambda + Queue: The power duo
In complex scenarios, lambda functions combined with Queues carry worker's return value safely to the main thread.
Asyncio candy wrap of future
Wrap futures from ThreadPoolExecutor
with asyncio.wrap_future
to make future objects asyncio-friendly.
Stellar management of threads and their return values paves the way to a robust application that's not just performant, but also reliable and maintainable.
Was this article helpful?