Question:
A short question on asincio: Coroutines run on the same thread?
Always different threads, always one thread, or threads are allocated as needed? Does it depend on the implementation of loop
?
This question is related to using threading.local
.
Answer:
Yes. :
An event loop runs in a thread and executes all callbacks and tasks in the same thread.
asyncio.get_event_loop()
returns the event loop corresponding to the current context. By default, this is the current thread, i.e. one cycle per thread . When called from a coroutine, a loop is returned that executes that coroutine :
When called from a coroutine or a callback (eg scheduled with call_soon or similar API), this function will always return the running event loop.
Most methods and classes in asyncio
are not thread safe. If you want to run a task in a loop from another thread, you can use asyncio.run_coroutine_threadsafe() .
Even within a single thread, there can be issues with changing non-local state when returning control to the event loop ( await
). See PEP 550 — Execution Context . Python 3.7 has a contextvars
module that implements PEP 567 — Context Variables .