Boost Users :
From: Pablo Aguilar (pablo.aguilar_at_[hidden])
Date: 2005-08-17 18:12:27
FYI Matthew Wilson gave a technique (in "Imperfect C++") for handling this,
by turning the mutex initialization into an integer initialization (that
doesn't have a problem with [multiple] simultaneous threads entering the
It uses STLSoft's spin_mutex, and looks pretty much like what you have
// static boost::mutex m;
// boost::mutex::scoped_lock l(m);
static int spin_count = 0; // No race condition initializing an
spin_mutex mutex(&spin_count); // Build the mutex on top of the static
static boost::shared_ptr<T> p(new T);
This assumes, of course, you can (and are willing to) use STLSoft...
"James E Taylor" <james_at_[hidden]> wrote in message
>I hope this isn't a stupid question, but....
> Is the boost mutex constructor thread-safe?
> I am writing a singleton template and trying to avoid the static
> initialisation/destruction order fiasco.
> I envisage two threads accessing a function like this concurrently:
> template<typename T>
> static boost::mutex m;
> boost::mutex::scoped_lock l(m);
> static boost::shared_ptr<T> p(new T);
> return p;
> and my worry is that both threads could attempt to do the static
> initialisation of m concurrently. Is there protection against this? Is
> it even possible to protect against this?
> I've tried to use boost::call_once, which would give sufficient guarantees
> but it's quite inflexible as nothing can be passed to or from the function
> being called.
> I know that integral types (like a pthread_t) of static storage are
> initialised before main() and before constructors of statically allocated
> objects are called, which means there would be no problem using a
> pthread_t above. However, constructors of objects of static storage are
> called at a time when there could be multiple threads running.
> Am I worrying about nothing? Or is there a problem here?
> James E Taylor
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net