Fix Python – How to get the return value from a thread in Python?


Asked By – wim

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!',))
return_value = thread.join()

The “one obvious way to do it”, shown above, doesn’t work: thread.join() returned None.

Now we will see solution for issue: How to get the return value from a thread in Python?


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()

This question is answered By – Ramarao Amara

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0