Python dict lock?

Is there a data structure in Python that resembles a block dictionary? This data structure must meet the following requirements:

  • it must be randomly accessible and allow any item to be changed / deleted (not only the first or last)
  • it must have get () and put () locks
  • it must be thread safe

I would use a queue, but despite being blocked and thread safe, it is not randomly available. The dict also does not block (as far as my knowledge of Python is known). As an example, think about the fact that one producer stream adds key-value pairs to such a data structure (updating values ​​for existing keys, if they are already present, is the place where the queue will not cut it), and the worker blocks get () and consuming these key-value pairs as they appear. Many thanks!

edit: Assume that the producer of the CI server poll receives the project status pairs. It generates differences in project statuses and puts them in the above data structure. The worker takes these project status updates and displays them one by one as an animation on the screen.

class Producer: def generateProjectStatusChanges(): ... def updateSuperAwesomeDataStructure(changes): for (proj, stat) in changes: #queue won't do cause the update could take place in the middle of the queue #hence the dict behavior superAwesomeDS.putOrUpdate(proj, stat) def watchForUpdates(): changes = generateProjectStatusChanges() updateSuperAwesomeDataStructure(changes) time.sleep(self.interval) class Worker: def blockingNotifyAnimation(): ... def watchForUpdates(): while true: proj, stat = superAwesomeDS.getFirstPair() #or any pair really blockingNotifyAnimation(proj, stat) 
+5
source share
1 answer

Something in the following lines should do the trick (untested):

 class UpdatableBlockingQueue(object): def __init__(self): self.queue = {} self.cv = threading.Condition() def put(self, key, value): with self.cv: self.queue[key] = value self.cv.notify() def pop(self): with self.cv: while not self.queue: self.cv.wait() return self.queue.popitem() 

It uses a dictionary for the queue and a condition variable to serialize access and signaling between threads.

+2
source

Source: https://habr.com/ru/post/1205600/


All Articles