Python3 Asyncio shared resources between concurrent tasks

Cellydy picture Cellydy · Aug 5, 2016 · Viewed 7.4k times · Source

I've got a network application written in Python3.5 which takes advantage of pythons Asyncio which concurrently handles each incoming connection.

On every concurrent connection, I want to store the connected clients data in a list. I'm worried that if two clients connect at the same time (which is a possibility) then both tasks will attempt to write to the list at the same time, which will surely raise an issue. How would I solve this?

Answer

Andrew Svetlov picture Andrew Svetlov · Aug 5, 2016

asyncio does context switching only on yield points (await expressions), thus two parallel tasks are not executed at the same time.

But if race conditions are still possible (it depends on concrete code structure) you may use asyncio synchronization primitives and queues.