This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Meyers Item 4 Singleton in presence of threading


Patrick Horgan <phorgan1@yahoo.com> writes:
> T& getaccess()
> {
>     static T localT;
>     return localT;
> }
...
> 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?

gcc, at least (well, versions above 4.0), takes care to make such local
static initializations thread-safe.  I presume that other modern
compilers likely do the same.

To be sure though, look at the assembly output and see exactly what your
compiler generates... :]

-Miles

-- 
Pray, v. To ask that the laws of the universe be annulled in behalf of a
single petitioner confessedly unworthy.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]