Boost logo

Boost Users :

From: Bill Somerville (bill_at_[hidden])
Date: 2008-04-08 11:24:56


Anteru wrote:
> Hiho,
>
> I'm using the new Boost Threads for a Thread Pool, however, I've got
> some weird problems.
>
> The documentation of Condition::notify_one says it unblocks one of the
> threads waiting currently on the condition -- what happens if I have
> several threads waiting and I call notify_one twice?
>
> It seems that on Windows/x64/VC9, only on thread wakes up if notify_one
> is called twice in a row. Is this right?
>
> Second, wait says: "The thread will unblock when notified by a call to
> this->notify_one() or this->notify_all(), or spuriously". Is it likely
> that a condition unblocks spuriously? After all, I'd expect to unblock
> only after calling notify_* and not "by accident". Is there any way to
> get diagnostic output when a wait has been called spuriously?
>
> The problem I'm having at the moment is: I have PIMPLed Boost.Thread
> behind some simple wrappers, and I'm using them like this here:
>
> Lock lock (mutex_);
>
> if (queue.empty ())
> {
> waitForItem.wait (lock);
> }
>
> with Lock being a wrapper for scoped_lock, mutex being a wrapper for
> mutex and waitForItem being a condition, and funnily enough it goes
> waiting even though there is an item in queue (i.e., queue.empty () ==
> false). I'm not sure where this is coming from (all access to queue is
> protected using mutexes), only candidate at the moment is that when
> inserting, I call notify_one, and if two items get inserted one right
> after the other, I assume that only one thread is woken up and hence the
> other remains waiting although there is an item in the queue.
>
> It works when I use notify_all (), but this does not smell right to me :/
>
I think it is a common misconception that condition variables can be
used alone to synchronize threads waiting for an event.

Idiomatic usage requires some element of state (often simply a boolean
value) to be changed before the condition is signalled. Then the
activated thread should check the state WHILE HOLDING THE LOCK that the
condition wait re-grants on exit. Only if the state is set should the
woken thread do the action for which it was waiting and resetting the
state. This model means that spurious returns from wait (for example
interrupted system calls in a *nix system) will not cause unwanted
behaviour.
> Thanks,
> Anteru
>

-- 
Bill Somerville
Class Design Limited

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