监视器同步:实现多个条件变量
我正在实施监视器同步。我想知道实现多个条件变量是如何工作的。 因此,条件变量具有 wait() 方法,该方法将其放入与该条件变量绑定的特定锁的等待队列中。因此,如果我有多个条件变量,每个等待调用是否都会创建自己单独的等待队列? 例如,如果我有:
lock = Lock()
A = Condition(lock)
B = Condition(lock)
C = Condition(lock)
def foo:
with lock:
while true:
A.wait()
def bar:
with lock:
while true:
B.wait()
def notifyA
with lock:
A.notifyAll()
那么我的问题是,当我们执行 A.notifyAll() 时,它是否只唤醒 A.wait 队列中的内容,或者有一个与锁关联的组合队列。
I am implementing monitor synchronization. I was wondering how does implementing multiple condition variables works.
So a condition variable has method wait() which puts it on the wait queue for a specific lock tied to this condition variable. So if I have multiple condition variables, do each wait call create its own separate wait queue?
For eg, if I have:
lock = Lock()
A = Condition(lock)
B = Condition(lock)
C = Condition(lock)
def foo:
with lock:
while true:
A.wait()
def bar:
with lock:
while true:
B.wait()
def notifyA
with lock:
A.notifyAll()
So my question is that when we do A.notifyAll(), does it only wake up stuff in the A.wait queue or this there a combined queue for associated with the lock.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
A.notifyAll()
应该只唤醒运行foo()
的线程。您的线程wait()
所在的等待队列是条件变量的一部分,而不是锁的一部分。锁确实有自己的等待队列,但它仅由尝试获取锁的线程使用。当您的线程在 CV 中休眠时,它不会持有锁,并且不会尝试重新获取锁,直到另一个线程调用notify()
或类似的方法。也就是说,您应该编写代码来假设
B.wait()
实际上可以随时唤醒。实际上,这意味着重新检查线程正在等待的条件:A.notifyAll()
should only wake up the thread runningfoo()
. The wait queue your threads arewait()
-ing in is part of the condition variable, not the lock. The lock does have its own wait queue, but it's only used by threads trying to acquire the lock. When your thread sleeps in a CV, it doesn't hold the lock, and won't try to reacquire it until another thread callsnotify()
or similar.That said, you should write your code to assume that
B.wait()
could in fact wake up at any time. Practically that means re-checking the condition the thread is waiting on: