简体   繁体   English

线程局部全局作用域变量

[英]Thread local global scope variable

Consider the following code: 考虑以下代码:

#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 演示

Since a has thread storage duration, we have at least three different objects, denoted by a and used in first , second and main threads. 由于a具有线程存储持续时间,因此我们至少有三个不同的对象,用a表示并在firstsecondmain线程中使用。 We don't use a inside third . 我们不使用athird Is there zero-initialized a which can be used in third? 是否存在可以在第三个中使用的零初始化a I ask this question because I can't find anything about this in the Standard: 我问这个问题是因为我在标准中找不到关于此的任何内容:

Non-local variables with thread storage duration are initialized as a consequence of thread execution. 具有线程存储持续时间的非局部变量由于线程执行而被初始化。

Is it implementation defined? 实现定义了吗?

N3337, 3.7.2.2 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. 具有线程存储持续时间的变量应在其第一次使用odr(3.2)之前初始化,如果构造,则应在线程退出时销毁。

3.2.2 is too long to copy it here, but essentially, it can´t be "odr-used" if it doesn´t appear in the executed code. 3.2.2太长了,无法在此处复制,但是从本质上讲,如果它没有出现在执行的代码中,则不能被“奇怪地使用”。 So it is not (necessarily) initialized with something. 因此,它(不必)使用某些东西初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM