Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Local static variable define is thread safe?

Reply
Thread Tools

Local static variable define is thread safe?

 
 
kiluyar
Guest
Posts: n/a
 
      05-22-2007
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?

 
Reply With Quote
 
 
 
 
Alf P. Steinbach
Guest
Posts: n/a
 
      05-22-2007
* kiluyar:
> 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?
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Static inline functions with static local variables Martin Wells C Programming 10 10-08-2007 03:38 PM
About typedef -- define the function pointer or define function model? robin liu C Programming 3 04-21-2006 03:26 PM
static variable:declare and define linq936@hotmail.com C++ 1 04-06-2006 05:31 PM
How to define a define that defines some defines ? theotyflos C Programming 3 02-19-2004 05:07 PM
a static local variable in a static method is thread local storage? Patrick Hoffmann C++ 3 08-08-2003 02:37 PM



Advertisments