Meyers Item 4 Singleton in presence of threading

Tim Prince
Sat Nov 20 20:33:00 GMT 2010

On 11/20/2010 12:24 AM, Patrick Horgan wrote:
> In Scott Meyers' Effective C++ Item 4, Scott recommends using 
> something like:
> T& getaccess()
> {
>     static T localT;
>     return localT;
> }
> so that a static local is used instead of a static global to access 
> the global object and you can be sure it's initialized before used.
> What happens in the presence of threading?  What if two threads enter 
> getaccess and exit in different orders?  I'm ignoring here any 
> threading issues that a T itself may have, and only thinking about the 
> local static initialization itself.
> Would the local t get initialized more than once?
> The language says that t would only be initialized the first time the 
> routine is called, so if the first one sleeps and a second one gets in 
> and out before the first thread gets rescheduled, can it return a 
> reference to localT before localT is initialized?
> Patrick
This doesn't match Item 4 in my (older?) Meyers.
As you have presented this, the threads would have a race condition on 
access to localT.  I see only an initialization at compile time, so it 
appears to be initialized prior to thread creation.   In view of the 
race, when threads modify the value, it's indeterminate whether a thread 
will read the value set by itself or by another thread.
I don't know whether others might share my view that since gomp is part 
of gcc, questions on OpenMP, or, possibly, std::thread, would be more on 
topic than questions about some unspecified threading method.

Tim Prince

More information about the Gcc-help mailing list