c++ - 线程局部全局作用域变量

标签 c++ multithreading storage-duration

考虑以下代码:

#include <iostream>
#include <thread>

using std::cout;
using std::thread;

thread_local int a;

void foo()
{
    a = a + 1;
    cout  << a << "\n";
}

void bar()
{
    cout << a << "\n";
}

void baz()
{
    cout << "Something\n";
}

int main()
{
    thread first(foo);
    thread second(bar);
    thread third(baz);
    second.join();
    first.join();
    third.join();
    cout << a;
}

Demo

由于 a 具有线程存储持续时间,我们至少有三个不同的对象,用 a 表示并用于 firstsecond 线程。我们不在 third 中使用 a。有没有零初始化的a可以用在third中?我问这个问题是因为我在标准中找不到任何相关内容:

Non-local variables with thread storage duration are initialized as a consequence of thread execution.

是否定义了实现?

最佳答案

N3337, 3.7.2.2

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.

3.2.2 太长了,不能在这里复制它,但本质上,如果它没有出现在执行的代码中,它就不能被“使用”。所以它没有(必须)用某些东西初始化。

关于c++ - 线程局部全局作用域变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24701438/

相关文章:

c++ - 将新放置到缓冲区后,缓冲区和实例是否具有相同的 void* 地址?

c++ - 我是否正确使用指针和数组?

c# - 控制台输出到文本框

c++ - 引用是否有存储位置?

带内存的 C++ 宏

c++ - 是 vswprintf_s 缓冲区大小或 numberofElements 中的第二个参数

c - 从两个不同索引处的 2 个不同线程写入 float 组是否安全?

C 多线程与 pthread

arrays - 在C中初始化局部数组变量

c++ - 线程上下文的静态存储对象优化