Palace Chan
Palace Chan

Reputation: 9203

thread local statics in c++ and gcc

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

Answers (1)

queen3
queen3

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:

  • gcc will protect initialization but not usage of the static; the variable is initialized the first time block is entered
  • const does not affect it, as long as it's static storage
  • __thread vars are initialized using their own initialization and are not protected by any extra lock (as pointed in comments by jmetcalfe)
  • static should be at block scope, so any block will do, even just {} pair.
  • (by Aurelien, see comments) someFunc will be called only once

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

Related Questions