How do I run two coroutines in parallel?#
Keep track of the tasks and make sure they terminate or you cancel them when the connection terminates.
Why does my program never receive any messages?#
Your program runs a coroutine that never yields control to the event loop. The coroutine that receives messages never gets a chance to run.
await statement in a
for or a
while loop isn’t enough
to yield control. Awaiting a coroutine may yield control, but there’s no
guarantee that it will.
send() only yields
control when send buffers are full, which never happens in most practical
async def producer(websocket): message = generate_next_message() await websocket.send(message) await asyncio.sleep(0) # yield control to the event loop
asyncio.sleep() always suspends the current task, allowing other tasks
to run. This behavior is documented precisely because it isn’t expected from
See issue 867.
Why am I having problems with threads?#
You shouldn’t use threads. Use tasks instead.
If you believe that you need to run websockets in a thread and some logic in
another thread, you should run that logic in a
If you believe that you cannot run that logic in the same event loop because it
will block websockets,
run_in_executor() may help.
Why does my simple program misbehave mysteriously?#
This may lead to messages getting send but not received, to connection
timeouts, and to unexpected results of shotgun debugging e.g. adding an
unnecessary call to
makes the program functional.