监视器同步:实现多个条件变量

发布于 2024-09-25 07:39:27 字数 517 浏览 4 评论 0原文

我正在实施监视器同步。我想知道实现多个条件变量是如何工作的。 因此,条件变量具有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

追风人 2024-10-02 07:39:27

A.notifyAll() 应该只唤醒运行 foo() 的线程。您的线程wait()所在的等待队列是条件变量的一部分,而不是的一部分。锁确实有自己的等待队列,但它仅由尝试获取锁的线程使用。当您的线程在 CV 中休眠时,它不会持有锁,并且不会尝试重新获取锁,直到另一个线程调用 notify() 或类似的方法。

也就是说,您应该编写代码来假设 B.wait() 实际上可以随时唤醒。实际上,这意味着重新检查线程正在等待的条件:

    with lock:
        while not ready:
            B.wait()
        # Do stuff with protected data

A.notifyAll() should only wake up the thread running foo(). The wait queue your threads are wait()-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 calls notify() 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:

    with lock:
        while not ready:
            B.wait()
        # Do stuff with protected data
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文