在Python中阻止dict?
Python中是否有类似于块字典的数据结构?此数据结构必须满足以下要求:在Python中阻止dict?,python,multithreading,dictionary,Python,Multithreading,Dictionary,Python中是否有类似于块字典的数据结构?此数据结构必须满足以下要求: 它必须是随机可访问的,并允许修改/删除任何元素(不仅仅是第一个或最后一个) 它必须有一个阻塞get()和put() 它必须是线程安全的 我会使用队列,但是,尽管它是阻塞的和线程安全的,但它不是随机访问的。dict也没有阻塞(就我的Python知识而言)。 例如,假设一个生产者线程将键值对添加到这样的数据结构中(如果已有键值对,则更新现有键值-这是队列不会剪切它的地方),以及一个工作者阻塞get()并在这些键值对可用时使
- 它必须是随机可访问的,并允许修改/删除任何元素(不仅仅是第一个或最后一个)
- 它必须有一个阻塞get()和put()
- 它必须是线程安全的
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)
以下几点应该可以做到(未经测试):
它使用一个队列字典和一个条件变量来序列化线程之间的访问和信令。这里也可以将
与self.cv
一起使用,而不是acquire
/release
。当一件不易损坏的物品放入dict时,您的代码是危险的;将与
一起使用可确保安全。在Python3.2+上还有wait\u for
,这是一种语法上的糖分。最后,请注意,notify
可能需要变成notify\u all
,如果您使用它来等待某个特定键变为可用,而不使用多个条件变量。
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()