llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

thread-local static variable unnecessarily constructed again

Open eyalroz opened this issue 7 years ago • 4 comments

Bugzilla Link 42111
Resolution FIXED
Resolved on Jun 04, 2019 17:04
Version 8.0
OS Linux
CC @dwblaikie,@DougGregor,@jyu2-git,@zygoloid

Extended Description

Relevant StackOverflow question: https://stackoverflow.com/q/52471237/1593077

Consider the following program:

#include #include

using std::cout; using std::endl;

template class Something { public: struct TLBookkeeping { TLBookkeeping() { std::cout << "TLBookkeeping() " << std::this_thread::get_id() << std::endl; } };

  static void foo();
  static thread_local TLBookkeeping bookkeeping_;

};

template thread_local typename Something::TLBookkeeping Something::bookkeeping_;

template void Something::foo() { std::cout << &bookkeeping_ << std::endl; std::cout << &bookkeeping_ << std::endl; }

namespace { struct Struct {}; }

int main() {
Something::foo(); }

If we compile and run it, we get:

TLBookkeeping() 140713161373504 0x7ffa55ffb73f TLBookkeeping() 140713161373504 0x7ffa55ffb73f

i.e. the static TLBookeeping variable is constructed twice. IIANM, this shouldn't happen; and compiling with GCC doesn't cause this behavior.

eyalroz avatar Jun 03 '19 10:06 eyalroz

Fixed in r362562.

Yes, because that thread local variable has internal linkage(eg. inside unnamed name space), thread not safe, need guard var for thread safe.

jyu2-git avatar Jun 04 '19 22:06 jyu2-git

the initialization guard for globals with internal linkage.

I don't know what the "initialization guard" is, but ok. I'll also repeat the observation by @​Curious in his Stackoverflow question: If you take struct Struct out of the anonymous namespace (give it external linkage?), the bug disappears.

eyalroz avatar Jun 04 '19 19:06 eyalroz

We're optimizing away the initialization guard for globals with internal linkage. That's incorrect for thread_locals, because the initialization function is called once per use not once per definition.