|
Boost : |
Subject: Re: [boost] [Boost.utility]
From: Thomas Klimpel (Thomas.Klimpel_at_[hidden])
Date: 2010-01-26 11:45:25
Andrew Chinkoff wrote:
> Below is the typical realization of A::Instance():
>
> static A& Instance()
> {
> if (instance_ == NULL)
> {
> boost::mutex::scoped_lock locker(mtx_); // this is the thread safe cost!
> instance_ = new A();
> }
> return *instance_;
> }
> [...]
> Did I miss the point?
I guess the people sent you references with the expectation that you actually read them.
The "typical realization of A::Instance()" you presented has two serious race conditions.
1) As implemented above, more than one thread can try to create the instance of A, and the last one trying will be the one that creates the instance that will finally survive. The other instances will live forever, since no reference to them exists any more, and nobody is responsible to delete them.
2) Even worse and much more difficult to fix, you will have a hard time forcing the compiler to not first allocate the space for the instance of A, then set the instance_ pointer to it, and then construct A in the newly allocated space. (And the next thread will see that instance_ is no longer NULL, and use the not yet constructed object.) You would basically need support for atomic operations to force the compiler to do the thing you want it to do.
Regards,
Thomas
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk