Two Threads sharing a mutex

Hi there, please help me out. Seems I lost my brain over the last weekend. ;-)) I'm trying to get myself familiar with the boost::thread lib, by reading an article by Bill Kempf published in the C++ magazine in 2002. Here in listing no. 4 he is using two thread (a reader and a writer ) to access a buffer. In the put() and get() he is using one mutex. If the buffer is empty he uses a condition variable to block the mutex. I don't understand how a writer can then enter the put() and write an item into the buffer? The mutex was just blocked by the reader thread? I guess my question is more fundamental to threads. But hopefully there is someone that can help me out. Thanks ahead, Christian

G'day.
Quoting Christian Henning
If the buffer is empty he uses a condition variable to block the mutex. I don't understand how a writer can then enter the put() and write an item into the buffer? The mutex was just blocked by the reader thread?
I haven't read the article, but I think your misunderstanding might be about how condition variables work. The wait() method on a Boost condition variable is passed a lock on the protecting mutex. It does two things (atomically): suspends the thread and releases the lock. When a waiting thread is woken by the condition being signalled, the opposite happens: the lock is re-acquired and the thread is woken up. So as I understand the code that you're describing, the reason why the writer can enter is that the reader does not hold the lock while it's waiting on the condition variable. Does that help? Cheers, Andrew Bromage

Thank you very much, that is what I was looking for. It's sometimes hard when the documentation of boost::thread is so little. I think it's important to add it. Christian PS: The code can be downloaded at www.cuj.com/code, select the May 2002 link

Hi there, please help me out. Seems I lost my brain over the last weekend. ;-))
I'm trying to get myself familiar with the boost::thread lib, by reading an article by Bill Kempf published in the C++ magazine in 2002.
Here in listing no. 4 he is using two thread (a reader and a writer ) to access a buffer. In the put() and get() he is using one mutex.
I can't see the article, but I guess I know what's happening.
If the buffer is empty he uses a condition variable to block the mutex. I don't understand how a writer can then enter the put() and write an item into the buffer? The mutex was just blocked by the reader thread?
The condition.wait() is passed the lock. So inside the condition-wait code, the mutex of the lock is unlocked. The mutex will stay unlocked for the duration of the wait-call and then be locked again. /Peter
I guess my question is more fundamental to threads. But hopefully there is someone that can help me out.
Thanks ahead, Christian
participants (3)
-
ajb@spamcop.net
-
Christian Henning
-
Peter Koch Larsen