gpt4 book ai didi

c++ - 什么时候初始化 `thread_local` 全局变量?

转载 作者:太空狗 更新时间:2023-10-29 23:11:59 25 4
gpt4 key购买 nike

考虑以下示例(为简单起见省略了 cout 上的锁守卫)。

#include <future>
#include <iostream>
#include <thread>

using namespace std;

struct C
{
C() { cout << "C constructor\n";}
~C() { cout << "C destructor\n";}
};

thread_local C foo;

int main()
{
int select;
cin >> select;
future<void> f[10];
for ( int i = 0;i < 10; ++i)
f[i] = async( launch::async,[&](){ if (select) foo; } );
return 0;
}

在 clang 和 gcc 上,如果用户输入“0”,该程序不输出任何内容,而如果用户输入非零,则打印 Constructor/Destructor 10 次数字。另外 clang 提示一个明显的未使用表达式结果。

因为 thread_local 存储生命周期应该跨越整个线程的生命周期,所以我希望无论用户输入如何,foo 变量都会在每个线程中初始化。

我可能想要一个 thread-local 变量,其唯一目的是在构造函数中产生副作用,标准要求 thread_local 对象是在第一次使用时初始化?

最佳答案

标准允许这种行为,但并不保证。来自 3.7.2/2 [basic.stc.thread]:

A variable with thread storage duration shall be initialized before its first odr-use (3.2) and, if constructed, shall be destroyed on thread exit.

也有可能对象是在其他时间构造的(例如在程序启动时),因为“首次使用之前”的意思是“在任何时候,只要它在之前”,而不是“就在之前”。

关于c++ - 什么时候初始化 `thread_local` 全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48671113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com