Search code examples
c++gccthread-safetymingw-w64thread-local-storage

Why is a static thread_local object in C++ constructed twice?


This code:

#include <iostream>
#include <thread>
#include <mutex>

struct Singl{
    Singl(Singl const&) = delete;
    Singl(Singl&&) = delete;

    inline static thread_local bool alive = true;

    Singl(){
        std::cout << "Singl() " << std::this_thread::get_id() << std::endl;
    }
    ~Singl(){
        std::cout << "~Singl() " << std::this_thread::get_id() << std::endl;
        alive = false;
    }
};

static auto& singl(){
    static thread_local Singl i;
    return i;
}

struct URef{
    ~URef(){
        const bool alive = singl().alive;
        std::cout << alive << std::endl;
    }
};


int main() {
    std::thread([](){
        singl();
        static thread_local URef u;
    }).join();

    return 0;
}

Has the following output:

Singl() 2
Singl() 2
1
~Singl() 2
~Singl() 2

I'm compiling and running under Windows with mingw-w64 gcc7.2 POSIX threads.

Coliru has a different output: http://coliru.stacked-crooked.com/a/3da415345ea6c2ee

What's this? Something wrong with my toolchain / compiler, or is that how it should be? Why do I have two thread_local objects (or constructed twice?) on the same thread?


Solution

  • It's probably something wrong with your compiler or toolchain.

    With both clang++ 8 and g++ 8.2 on Linux (Devuan ASCII to be exact), the thread-local variable is constructed just once.