Boost logo

Boost :

From: John Maddock (john_at_[hidden])
Date: 2005-07-24 05:01:26


> This looks very nice. However, using static_mutex would create a
> dependency on Boost.Regex for all Spirit MT code. I hope static_mutex
> will eventually become a part of Boost.Thread.

Good point, I've been meaning to make it header only, but haven't had cause
to really up until now.

> I changed the offending code to use boost::call_once() for mutex
> initialization (following a suggestion Peter Dimov made in another
> thread related to a similar problem). The test passes on OSL2
> (darwin-gcc-3.3 toolset) now.

That call_once idea is really cunning. Embarrissingly I only invented
static_mutex because I couldn't think of a way of getting call_once to do
what I wanted!

Just thinking off the top of my head, I wonder if the technique could be
boilerplated:

template <class Mutex, class id>
Mutex& get_static_mutex(); // returns an instance of Mutex that is
unique to "id".

Extreme Usage Example:
~~~~~~~~~~~~~~~~~

template <class T1, class T2> struct mytag;

template <class T1, class T2>
void myproceedure(T1 t1, T2 t2)
{
  // get a mutex instance that is unique to this function, *and* the types
T1 and T2:
  boost::mutex m& = get_static_mutex<boost::mutex, mytag<T1,T2> >();
  boost::mutex::lock l(m);
  // thread safe code goes here:
  // etc....
}

Implementation:
~~~~~~~~~~~

All untried:

template <class Mut, class Tag>
Mut& do_get_mutex()
{
  static Mut m;
  return m;
}

template <class Mut, class Tag>
void call_once_proc()
{
  do_get_mutex();
}

template <class Mutex, class id>
Mutex& get_static_mutex()
{
  boost::once_flag once = BOOST_ONCE_INIT;
  boost::call_once(&call_once_proc<Mutex, id>, once);
  return do_get_mutex<Mutex, id>();
}

How does this look as an extension to Boost.Threads? Unless I've missed
something (!) it should work for any mutex type. Actually shouldn't this
work for any global variable that you want initialised in a thread safe
manner?

You know the more I think about this, the more I worry about what I've
missed, it can't be this simple can it?

Regards, John.


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