How can I asynchronously insert tasks to run in an asyncio
event loop running in another thread?
My motivation is to support interactive asynchronous workloads in the interpreter. I can't block the main REPL thread.
Example
My current flawed understanding says that the following should work. Why doesn't it? What is a better way to accomplish goal above?
import asyncio
from threading import Thread
loop = asyncio.new_event_loop()
def f(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
t = Thread(target=f, args=(loop,))
t.start()
@asyncio.coroutine
def g():
yield from asyncio.sleep(1)
print('Hello, world!')
asyncio.async(g(), loop=loop)
You must use
call_soon_threadsafe
to schedule callbacks from different threads:See https://docs.python.org/3/library/asyncio-dev.html#asyncio-multithreading for more information.
EDIT: Example of an interpreter supporting asynchronous workloads