Boost logo

Boost :

From: Anthony Williams (anthony_w.geo_at_[hidden])
Date: 2006-09-19 12:02:13

"Martin Bonner" <martin.bonner_at_[hidden]> writes:

> From: boost-bounces_at_[hidden]
> [mailto:boost-bounces_at_[hidden]] On Behalf Of Anthony Williams
>> The mutex is simple, and you can see the code in
>> boost/thread/win32/basic_mutex.hpp on the thread_rewrite branch.
> I'm missing something here (I hope).
>> The algorithm is:
>> init():
>> active_count=0;
>> no semaphore
>> lock():
>> atomic increment active_count
> At this point, thread2 atomically increments active_count as well, so it
> is now 2.
>> if new active_count ==1, that's us, so we've got the lock
>> else
>> get semaphore, and wait
> Both threads will go into this branch. Why don't they wait forever?

No. The atomic increments are atomic, and return the new value: we don't do an
extra read. One thread will see "1", and the other "2".

>> now we've got the lock
>> unlock():
>> atomic decrement active_count
>> if new active_count >0, then other threads are waiting,
>> so release semaphore.
> Alternatively,
> Thread A Thread B
> locks mutex
> atomic increment active_count (in lock)
> atomic decrements active_count (in unlock)
> new active_count > 0, so other threads are waiting
> release semaphore
> ... oops. What semaphore?

Sorry I didn't make it clear. If we go into this branch of unlock, we have to
call get_semaphore() to get the semaphore to release. This ensures that there
is one and only semaphore associated with this mutex, which is returned to all
callers, and is therefore released by the unlock().

Hope that makes things clearer.


Anthony Williams
Software Developer
Just Software Solutions Ltd

Boost list run by bdawes at, gregod at, cpdaniel at, john at