 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
kiluyar Guest
|
Posted: Tue May 22, 2007 9:10 am Post subject: Local static variable define is thread safe? |
|
|
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
|
Posted: Tue May 22, 2007 9:10 am Post subject: Re: Local static variable define is thread safe? |
|
|
* 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 |
|
 |
|
|
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
|
|