Boost logo

Boost :

From: William E. Kempf (wekempf_at_[hidden])
Date: 2003-04-23 09:35:42


Russell Hind said:
> thread currently allows various mutex implementations: I currently use
> boost::mutex and boost::recursive_mutex most often. On Win32
> boost::mutex is implemented using a CriticalSection. AFAIK, this is
> recursively enterable. recursive_mutex also uses a critical section,
> although with a little extra in the implementation.

The requirements for the mutex types don't specify what should happen if
you try and recursively lock them. This is an error no matter what
behavior is actually provided by an implementation, so specifying the
behavior would be a questionable decision. Basically, you'd have 3
choices:

1) Deadlock.
2) Recursively lock.
3) Do error checking of some sort (returns, exceptions, etc.).

The first two options aren't helpful, as they just produce different forms
of broken state according to the usage requirements, while the third is
only marginally useful with high overhead. The third option might be
useful in debug builds, but not as the default. The Boost.Threads
specification allows this, but doesn't require it.

> I was wondering if there was a way to stop mutex being recursive on
> Win32? I then looked into the source and saw that try_mutex uses a
> Mutex, not a critical section. Would this implementation not work for
> mutex?

Sure, but on Win32 MUTEXes are recursive as well. There is no
non-recursive locking mechanism on Win32 other than with SEMAPHOREs, which
have semantics that aren't fully compatible with Mutexes (specifically,
anyone can "unlock" the semaphore, not just the thread that "locked" it).

> Also, it appears that try_mutex uses a Mutex so that it can perform a
> wait with a timeout of 0 (ie. if it can't enter, return immediately).
> Could this not have been implemented with a critical section and use
> TryEnterCriticalSection? Why was the mutex approach used for one and
> not the other?

TryEnterCriticalSection is not portable. Specifically, it's not available
in the Win9x line.

-- 
William E. Kempf

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