Local static variable define is thread safe?

K

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?
 
A

Alf P. Steinbach

* 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... ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,185
Latest member
GluceaReviews

Latest Threads

Top