Boost logo

Boost :

From: Michael Glassford (glassfordm_at_[hidden])
Date: 2004-04-02 18:52:09


"Darryl Green" <Darryl.Green_at_[hidden]> wrote in message
news:4FCBBCDBF9232241B8D2031F2DD74DCBC01D96_at_BRISBANEMAIL1.brisbane.tabq.com...
> > -----Original Message-----
> > From: boost-bounces_at_[hidden]
> > [mailto:boost-bounces_at_[hidden]] On Behalf Of Stefan Seefeld
> > Sent: Friday, 2 April 2004 4:59 AM
> > To: boost_at_[hidden]
> > Subject: [boost] problem with global mutex object on windows
> >
> >
> > hi there,
> >
> > we'v run into a problem with the boost_thread mutex class,
> > when used as a global object.
> >
> > Imagine a singleton class as
> >
> > class Singleton
> > {
> > public:
> > static Singleton *GetInstance();
> > static void Destroy();
> > private:
> >
> > struct Guard
> > {
> > ~Guard() { Singleton::Destroy();}
> > };
> > static Singleton *instance;
> > static Guard guard;
> > static boost::mutex mutex;
> > };
> >
> > where the internal access to 'instance' is serialized by means of
the
> > mutex (inside methods GetInstance() and Destroy()).
> >
> > It is the Singleton::Guard destructor that is responsible to free
> > the instance (if it isn't destructed already). It, too, uses the
> > mutex to protect access.
> >
> > In a specific context on windows xp it happened that the mutex
> > variable was destructed before the guard, leading to a global
>
>
> 3.6.2 Objects with static storage duration .. shall be initialized
in
> the order in which their definition appears in the translation unit.

Yes.

> 3.6.3 ... These objects are destroyed in the reverse order of the
> completion of their constructor or of the completion of their
dynamic
> initialization.

Yes.

> So as long as the Singleton::Guard definition is before the
definition
> of the mutex it should work. I assume that despite having the
> definitions in that order it doesn't work? Does that make it a
compiler
> bug or am I missing something?

So unless I'm being dense, wouldn't you want to have the definition of
the Guard *after* that of the mutex? That way the mutex would be
created before the Guard and destroyed after the guard. Since the
guard uses the mutex (via the call to Destroy), this seems like a good
idea.

> In any case, I'm not convinced that this is sufficient to make your
> singleton useful. Do you know that GetInstance isn't called by the
> constructor of a static object? Do you know that no other threads
(which
> might call GetInstance) are started prior to the mutex being
> constructed?
>
> I haven't tried to get a truly thread-safe singleton working - I
> remember several discussions about it here - but I'm not sure that
any
> of them resulted in an efficient working solution?
>
> Sorry - perhaps not an altogether helpful response.
>
> Darryl.


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