views:

28

answers:

1

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.

A: 

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
Karmastan