2

I have a multithreaded app in which I need to use a global dict to remember and handle requests.

The problem is, I am not supposed to perform the same request twice, so I need dict to be able to test if the key exists. if not, insert it, if it does, report error.

All code runs in python so GIL should not be relevant.

Is that feasible in python?

Here lock would work but I am trying to find a more natural way to solve it.

Jason Hu
  • 6,239
  • 1
  • 20
  • 41

1 Answers1

0

You can surely create a dictionary and share it among the threads, but you should protect each access to the dictionary (be it read or write) with a lock.

Here lock would work but I am trying to find a more natural way to solve it.

The usage of synchronization primitives such as locks is the natural way to implement a reliable architecture involving concurrency.

That being said, making sure that a certain request is not made twice can be approached on various levels. If you are doing it with a dictionary like described, you need to insert the identifier right before performing the request. Pseudo code:

with lock.acquire():
    if url in d:
        return # do not perform request
    d.[url] = True

perform_request(url)

If the request failed, you might want to remove the key from dict again (not without acquiring the lock, of course).

Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130