Boost logo

Boost :

From: Anthony Williams (anthony_w.geo_at_[hidden])
Date: 2006-12-11 03:28:55


Yuval Ronen <ronen_yuval_at_[hidden]> writes:

> Roland Schwarz wrote:
>> Yuval Ronen wrote:
>>> I will gladly put my code here to be scrutinized by the experts on this forum (after the weekend, as the code is at work, and I'm
>>> at home now :-) ), but I fear that they will little incentive to do it.
>> Can't tell. Possibly yes. You will need to try.
>
> Ok, if anyone is still interested, here's my implementation of CV for Windows. It's very simple, maybe too simple, and I guess it's
> far less interesting than the code just posted by Chris Thomasson, but here it is anyway.
>
> void wait()
> {
> assert(m_mutex.isLocked());
> m_waitersCount++; // line A
> m_mutex.unlock();
> m_sem.lock(); // line B
> m_mutex.lock(); // line C
> }
>
> void broadcast()
> {
> assert(m_mutex.isLocked());
> if (m_waitersCount > 0)
> {
> m_sem.unlock(m_waitersCount); // line D
> m_waitersCount = 0;
> }
> }

Unfortunately, it is susceptible to the "stolen wakeup" problem. If
m_waitersCount is non-zero, the semaphore is incremented on line D. This will
wake the appropriate number of waiting threads, but not immediately. Threads
waiting on a semaphore will not be woken until they are next scheduled. Thus,
a new thread might call wait, increment the waitersCount (line A) and acquire
the (line B) before all the threads currently waiting have been woken.

There are two solutions to this that I can think of. The first is to have some
kind of lock which prevents additional threads from waiting until all the
notified threads have been woken.

The second is what Chris Thomasson talks about --- swapping out the "wait set"
for a new one on notify, so that no new threads can be added to that waitset,
even if the notified threads haven't all woken up. This is the technique used
in the win32 condvar implementation currently on the thread_rewrite branch.

Anthony

-- 
Anthony Williams
Software Developer
Just Software Solutions Ltd
http://www.justsoftwaresolutions.co.uk

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk