Boost logo

Threads-Devel :

From: Anthony Williams (anthony_at_[hidden])
Date: 2006-03-06 05:56:10


David Abrahams <dave_at_[hidden]> writes:

> Matt Hurd <matt.hurd_at_[hidden]> writes:
>>>On Thursday 02 March 2006 00:58, Anthony Williams wrote:
>>> I therefore suggest that we supply two mutex types, one of which is POD,
>>> and requires a static initializer, and one of which has a default
>>> constructor and a destructor. Of course, if we equip the first one with
>>> explicit initialize() and destroy() functions, then the second can just be
>>> a wrapper for the first that calls initialize() in the constructor, and
>>> destroy() in the destructor.
>>>
>>> I suggest that these two different variants are named boost::static_mutex
>>> and boost::mutex.
>
> Okay, two different types. But why is static_mutex needed? I still
> haven't seen a good argument, given that you need once routines to
> initialize the shared data anyway.

My primary concern is this:

There is lots of code that has mutex objects at global scope, or as static
objects at function scope. This code, particularly the latter, is open to race
conditions, if more than one thread can exist before the object has been
initialized. If we can provide mutexes that "just work" in such scenarios,
this is a step forward.

See
<http://www.opengroup.org/onlinepubs/000095399/functions/pthread_mutex_init.html#tag_03_537_08_04>
for the POSIX rationale for static initializers for mutexes.

The need for static mutexes might be reduced in C++, but there are still use
cases, and as Matt points out, the data locked by the mutex might not be
static if you're targetting environments where the total number of mutexes
is constrained to be less than the number of discrete data elements. In such a
scenario, you might share a single static mutex across all instances of a
class.

>>> I also have a "checked" version of basic_mutex (not in CVS), that checks
>>> which thread owns the mutex, and throws if the same thread tries to lock it
>>> twice, or a thread that doesn't own it tries to unlock it.
>
> Uh, throws? Why? Isn't that a precondition violation? If so,
> BOOST_ASSERT would be much more appropriate.

Yes. I just changed it to use BOOST_ASSERT.

Anthony

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

Threads-Devel list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk