Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug in clang thread_local initialization

The following code should be creating the in-class thread_local only once, but it ends up initializing it on every access

#include <iostream>
#include <thread>

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

template <typename T>
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 <typename T>
thread_local typename Something<T>::TLBookkeeping Something<T>::bookkeeping_;

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

namespace {
struct Struct {};
}

int main() {    
    Something<Struct>::foo();
}

(https://wandbox.org/permlink/fgqCDHV0axKDRt89)

Interestingly the bug only shows when Struct is in an anonymous namespace.

Does someone know if this is a clang bug (gcc does it right - https://wandbox.org/permlink/hsxRj8OdYbt4Eeck) or an inherently incorrect usage of thread_local? If the latter, what is the correct usage? If the former, what exactly is the bug? And is this documented somewhere? Should we open a bug report?

like image 208
Curious Avatar asked Sep 23 '18 23:09

Curious


Video Answer


1 Answers

When you find that a compiler causes runtime behavior which you are relatively certain is incorrect; and another popular compiler does not cause that same behavior - that is sufficient, IMHO, in order to file a bug against said compiler.

As @SamVarshavchik suggestions, you:

  1. Visit LLVM's bug tracker
  2. Create an account if you don't have one
  3. Look for duplicates (e.g. using the term "thread-local")
  4. If you don't find one - you file a bug

I've done just that, so now we have bug 42111.

At worst - it'll be marked as a dupe.

edit: It was not a dupe, and has just now (June 5th 2019) been fixed.

like image 162
einpoklum Avatar answered Oct 21 '22 05:10

einpoklum