Boost Users :
From: Vladimir Prus (ghost_at_[hidden])
Date: 2006-02-03 01:29:35
Matt Schuckmann wrote:
> Hi, actually I've discovered that isn't even right the work thread needs
> to lock the mutex before it sets the worker_thread_finished_working flag
> to true.
Sure, all accesses to shared variables must be protected by a mutex.
> You can also change the boolean flag to a predicate and use the form of
> wait that takes a predicate and implements the while loop for you.
> The key is the worker thread must hold mutex1 while it changes the state
> flag/predicate, otherwise notify could be called between the check in
> the while loop and call to wait and the deadlock would occur.
> I'm kind of bothered that the documentation doesn't state this.
Yes, the documentation is a bit lean on this topic. When I was reading it
for the first time I was completely confused.
> This whole issue make me think that this problem could be much more
> easily solved with with a binary semaphore or a non recursive mutex.
> Then it doesn't matter if the worker thread gets done before the master
> thread starts to wait.
Yes, for a pair of threads, and your use case, semaphore could work. But I
think condition variables scale much better. With binary semaphore you must
be very carefull to up the semaphore exactly when the waiting thread needs
to wake. Since condition.notify_all just means "something has changed" and
the woken thread decides itself if the wait condition is satisfied, it can
be easier to get right. You just call notify_all whenever anything changes.
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net