Move blocking things to own thread#
Blocking calls can be sent to a thread for execution whilst offering an asyncio interface to deal with
Warning
Note however, that there is no way to automagically interrupt the function executed in the thread, if it’s not designed that way.
So cancelling this task is technically possible, but without any effect.
import asyncio
import time
task = asyncio.create_task(
asyncio.to_thread(blocking_wait_for, 1) # creates coroutine
)
await task
print(task.result())
Done waiting for 1 seconds.
1