pythonmultithreadingfunctionreturn-valuepython-multithreading

How to get the return value from a thread?


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.


Solution

  • 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:

    import concurrent.futures
    
    def foo(bar):
        print('hello {}'.format(bar))
        return 'foo'
    
    with concurrent.futures.ThreadPoolExecutor() as executor:
        future = executor.submit(foo, 'world!')
        return_value = future.result()
        print(return_value)