I am trying to understand the python asyncio's call_soon_threadsafe API, but failed, with below example code, if my simple
coroutine want to return something, how should i get the returned value from the caller side?
import time
import asyncio as aio
import uvloop
from threading import Thread
aio.set_event_loop_policy(uvloop.EventLoopPolicy())
async def simple(a, fut:aio.Future):
await aio.sleep(a)
return fut.set_result(a)
def delegator(loop):
aio.set_event_loop(loop)
loop.run_forever()
loop_exec = aio.new_event_loop()
t = Thread(target=delegator, args=(loop_exec,))
t.start()
if __name__ == '__main__':
start_time = time.time()
fut = loop_exec.create_future() # tried to get back returned value by future
handle = loop_exec.call_soon_threadsafe(aio.ensure_future, simple(3, fut))
res = aio.wait_for(fut, 10)
print('Time consumed: {}s'.format(time.time() - start_time))
print('>>>>>>>>>>', res)
# Output
Time consumed: 3.2901763916015625e-05s
>>>>>>>>>> <generator object wait_for at 0x110bb9b48>
As u can see i was trying to get back the returned value by passing in a future to that coroutine which run in a different thread, but still don't know how to get it properly.
Basically two questions:
- With above example code how can i get back the returned value from the caller side?
- What's the actual use case for this
call_soon_threadsafe
, just feelrun_coroutine_threadsafe
is more convenient to use and it is able to cover almost all the cases i can imagine in this kind of different thread coroutines interaction.