Reputation: 9203
I am trying to understand the behavior of local statics with gcc and c++ (pre c++11 and post). A lot of times, in a member function I find myself doing something like so:
struct Foo
{
void foo()
{
static const bool bar = someFunc();
//etc
}
};
For example where someFunc()
is getenv("SOME_ENV_VAR")
. In the above code, what are the rules governing bar
? I believe, but do not have a reference, that gcc will compile a synchronization mechanism (not sure what) to protect the above local static from multiple threads. How do things change if it is no longer const
? or if we make it thread local with __thread
? And if foo()
is not a member function?
Upvotes: 2
Views: 622
Reputation: 15521
The rules are actually defined by C++ std and not gcc: http://cpp0x.centaur.ath.cx/stmt.dcl.html
I'd say that:
There're other issues like re-entering from recursion and no deadlocks allowed, it is all described in the link above. Also, C++ 03 and 11 std versions are a bit different on this topic.
Quote:
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization
$6.7.4, C++11
which means that it is thread-safe - but only in the new standard. Anyway in gcc this is controlled by -f[no-]threadsafe-statics option.
I'm also interested in the downvote, I mean, if you think the link is wrong it would be nice to tell why, so that me and others know.
Upvotes: 2