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

别等时光非礼了梦想. 提交于 2019-12-19 17:38:18

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/47226542/why-is-a-static-thread-local-object-in-c-constructed-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!