Warm tip: This article is reproduced from serverfault.com, please click

Is Python dictionary ayncio safe?

发布于 2020-12-03 11:17:42

I am using Python dictionary to store the data:

class Processor:
  def __init__(self):
     self.cache = {}

  async def add(name):
     data = await get_file(name)
     self.cache[name] = len(data)

  async def get_cache(name):
     return self.cache[name]

  async def clear():
     self.cache.clear()

  • In my main.py, I instantiate the Processor. Then I create 5 tasks.

  • Each task runs the processor.add(name) function every 30 seconds therefore each task has a different value for the name.

  • Every 1 hour, I have a task that runs and gets the data from the cache. Every 12 hours, I clear the cache via a task.

Is Python dictionary asyncio-safe? Do I need to add locks when saving/clearing/getting data?

Questioner
InfoLearner
Viewed
0
2020-12-03 19:21:39

General asyncio is "everything safe", since only one thing will execute at any one time. async tasks do cooperative multitasking; this means only one task executes at any one time, and whenever a task awaits or ends, the event loop coordinates for another task to be executed.

So yes, there will be no issue per se accessing a shared dictionary, beyond whatever business logic issues you may create for yourself.