-1

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?

InfoLearner
  • 14,952
  • 20
  • 76
  • 124
  • 3
    What is the difference between this question and [that question](https://stackoverflow.com/questions/65041691/is-python-dictionary-async-safe)? – mkrieger1 Dec 03 '20 at 11:27

1 Answers1

2

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.

deceze
  • 510,633
  • 85
  • 743
  • 889