My problem: starting a threaded function and, asynchronously, act upon the returned value
I know how to:
- start a threaded function with
threading
. The problem: no simple way to get the result back - get the return value from a threaded function. The problem: it is synchronous
What I would like to achieve is similar to JavaScript's
aFunctionThatReturnsAPromise()
.then(r => {// do something with the returned value when it is available})
// the code here runs synchronously right after aFunctionThatReturnsAPromise is started
In pseudo-Python, I would think about something like (modifying the example from the answer to the linked thread)
import time
import concurrent.futures
def foo(bar):
print('hello {}'.format(bar))
time.sleep(10)
return 'foo'
def the_callback(something):
print(f"the thread returned {something}")
with concurrent.futures.ThreadPoolExecutor() as executor:
# submit the threaded call ...
future = executor.submit(foo, 'world!')
# ... and set a callback
future.callback(the_callback, future.result()) # ← this is the made up part
# or, all in one: future = executor.submit(foo, 'world!', callback=the_callback) # in which case the parameters probably would need to be passed the JS way
# the threaded call runs at its pace
# the following line is ran right after the call above
print("after submit")
# after some time (~10 seconds) the callback is finished (and has printed out what was passed to it)
# there should probably be some kind of join() so that the scripts waits until the thread is done
I want to stay if possible with threads (which do things at their own pace and I do not care when they are done), rather than asyncio
(where I have to explicitly await
things in a single thread)