C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Local static variable define is thread safe?

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
kiluyar
Guest





PostPosted: Tue May 22, 2007 9:10 am    Post subject: Local static variable define is thread safe? Reply with quote



I have such a function:

class T
{
public:
T(){...//some operations}
};


T& GetInst()
{
static T t;
return t;
}

I'm not sure whether this is thread safe? If T's constructor has many
operations, when two thread entered this function early and later, is
there such scenario: the first thread is in T's constructor's, the
second thread define t again?
Back to top
Alf P. Steinbach
Guest





PostPosted: Tue May 22, 2007 9:10 am    Post subject: Re: Local static variable define is thread safe? Reply with quote



* kiluyar:
Quote:
I have such a function:

class T
{
public:
T(){...//some operations}
};


T& GetInst()
{
static T t;
return t;
}

I'm not sure whether this is thread safe? If T's constructor has many
operations, when two thread entered this function early and later, is
there such scenario: the first thread is in T's constructor's, the
second thread define t again?


The current version of the standard completely ignores the existence of
threads (and almost completely ignores the existence of dynamic
libraries). Therefore, the code is not thread safe. But you can use
environment-specific means to make e.g. the initialization of the static
variable thread safe. One simple way is to call GetInst() when only the
main thread has started, no others yet started. Another way, less
efficient, to ensure mutual exclusion for calls to GetInst. A third
way, if it's OK to let each thread have its own T object, to use thread
local storage. Boost threads support all three solutions. Of course,
the first one doesn't require any special support, so the support
consists of nothing, but by definition it's there... ;-)


--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.