Using a background thread with asyncio/futures with flask

dieter.maurer at online.de dieter.maurer at online.de
Fri Mar 22 13:28:25 EDT 2024


Thomas Nyberg wrote at 2024-3-22 11:08 +0100:
> ... `future` use across thread boundaries ...
> Here's an example using just the standard library that
> exhibits the same issue:

I think all `asyncio` objects (futures, tasks, ...)
are meant to be used in a single thread.
If you use them across different threads, you must do special things.

Note that an `await(future)` registers a callback at *future*.
When the future gets its result or exception, the registered callback calls
are scheduled via `self._loop.call_soon`.
`call_soon` must be called from the `asyncio` thread (to which `self._loop`
belongs). A different thread may schedule activities for a loop
but it must use `call_soon_threadsafe` (not `call_soon`).

I would expect that the forbidden `call_soon` call raises an exception
which for reasons I do not know appears to be hidden.


For use across thread boundaries, you likely will use
`concurrent.Future` (not `asyncio.Future`).
You can use `asyncio.futures._chain_futures` to associate
an `asyncio.Future` with a `concurrent.Future`.
Then the fate (result or exception set) of one will be reflected in the other.


More information about the Python-list mailing list