Boost logo

Threads-Devel :

From: David Abrahams (dave_at_[hidden])
Date: 2006-03-06 10:43:34

Anthony Williams <anthony_at_[hidden]> writes:

>> 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.

You completely miss (or at least fail to address) my point. Mutex
objects at global scope generally protect data at global scope.
Unless that data has a trivial ctor, its initialization needs to be
protected by a once routine anyway. Why not just use the same once
routine for the mutex too? I'm not sure it's worth making a whole
separate, usually-unsafe, mutex category just so we can handle the
case where global protected data has a trivial ctor.

  template <class T>
  class singleton
      static boost::tuple<boost::mutex&,T&> instance()
            &singleton::init, once);
          return get_instance();

      static void init() { get_instance(); }

      static boost::tuple<boost::mutex&,T&> get_instance()
          static boost::mutex sync;
          static T x;
          return tie(sync,x)

    static boost::once_flag once;

  boost::once_flag singleton::once = BOOST_ONCE_INIT;

> See
> <>
> for the POSIX rationale for static initializers for mutexes.

The POSIX rationale was written for a 'C' world; it may not be as
valid in a world where objects require construction.

> The need for static mutexes might be reduced in C++, but there are still use
> cases,

Yes. The question is whether they are general enough to warrant
supporting them. I contend that they are not, at least not in the
next few revisions of the library.

> 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.

Then use singleton<empty_tag_type> to get the "static" mutex.

Dave Abrahams
Boost Consulting

Threads-Devel list run by bdawes at, david.abrahams at, gregod at, cpdaniel at, john at