为什么在C ++中构造一个静态thread_local对象两次? [英] Why is a static thread_local object in C++ constructed twice?

查看:103
本文介绍了为什么在C ++中构造一个静态thread_local对象两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

#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;
}

具有以下输出:

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

我正在使用mingw-w64 gcc7.2 POSIX线程在Windows下编译和运行.

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

Coliru具有不同的输出: http://coliru.stacked-crooked.com/a/3da415345ea6c2ee

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

这是什么?我的工具链/编译器出问题了,还是应该这样?为什么在同一线程上有两个thread_local对象(或构造两次?)?

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?

推荐答案

您的编译器或工具链可能有问题.

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

对于Linux上的clang ++ 8和g ++ 8.2(确切地说是Devuan ASCII),线程局部变量仅构造一次.

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

这篇关于为什么在C ++中构造一个静态thread_local对象两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆