仅具有一个基础锁的读写锁? [英] Read-write lock with only one underlying lock?
问题描述
我已经使用Python的并发原语编写了读写锁(我认为!).我在SO或其他地方阅读的每个实现似乎都使用2个锁-一个用于读取,另一个用于写入.我的实现只包含一个用于读取的监视器,但是我可能缺少一些重要的内容-任何人都可以确认这将起作用吗?如果是这样,使用额外的写锁有什么好处?
I've written a read-write lock using Python's concurrency primitives (I think!). Every implementation I've read on SO or elsewhere seems to use 2 locks -- one for reads, and another for writes. My implementation contains only one monitor for reads, but I may be missing something crucial -- can anyone confirm that this will work? If so, what is the benefit to using an additional write lock?
这是经典的读写锁,优先考虑读者(可能会饿死作家).我使用虚拟缓存来演示读写操作.
This is the classic read-write lock with preference for readers (may starve writers). I use a dummy cache to demonstrate the reading and writing.
import threading as t
class ReadWriteCache(object):
def __init__(self):
self.cache = {}
self.reads = 0
self.read_cond = t.Condition(t.Lock())
def read(self, key):
with self.read_cond: # Register the read, so writes will wait()
self.reads += 1
result = self.cache[key]
with self.read_cond:
self.reads -= 1
if not self.reads:
self.read_cond.notify_all()
return result
def update(self, key, value):
with self.read_cond:
while self.reads:
self.read_cond.wait() # Wait for reads to clear
self.cache[key] = value # With read lock, update value
推荐答案
您没有使用单个锁.
您正在使用锁和条件变量
You are not using a single lock.
You are using a lock and a condition variable
self.read_lock = t.Condition(t.Lock())
条件变量也是并发原语.比锁更复杂.
A condition variable is a concurrency primitive too. A more complex one than a lock.
注意::请勿调用条件变量对象read_lock
note : please do not call a condition variable object read_lock
修改:
您的代码对我来说似乎是正确的,因为它解决了 第一个读者-作家问题 .正如您所说,这可能会使作家感到饥饿.这不是一个小问题.读者writer背后的逻辑是,读取可能比写入更多
额外的锁可以解决第二读者-作家问题,在这个问题中作家不会挨饿.确实,当有作家在等待资源时,读者必须等待.
edit:
Your code seems correct to me, as it solves the First readers-writers problem. As you said it may starve writer. This is not a small issue. The logic behind reader writer is that there may be a lot more reads than writes
An additional lock allow to solve the Second readers-writers problem, where a writer doesn't starve. Indeed, readers have to wait when there is a writer waiting for the resource.
这篇关于仅具有一个基础锁的读写锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!