本文介绍了什么时候是一个`thread_local`全局变量初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例(为简单起见,省略了 cout 中的锁定保护)。

Consider the following example (lock guards on cout omitted for simplicity).

#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 ',而如果用户输入非零数字,则它打印构造函数 / 10次。
另外,clang抱怨一个明显的未使用的表达式结果。

On both clang and gcc, this program outputs nothing if the user writes '0', while it prints Constructor/Destructor 10 times if the user inputs a non zero number.Additionally clang complains about an obvious non used expression result.

由于 thread_local 应该是跨越整个线程的生命,我期望 foo 变量在每个线程中被初始化,而不管用户输入。

Since a thread_local storage life-time is supposed to span the entire thread's life, I expected the foo variable to be initialized in every thread regardless of the user input.

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

I might want to have a thread-local variable for the sole purpose of having a side-effect in the constructor, does the standard mandates that a thread_local object is initialized on its first use?

推荐答案

标准允许这种行为,虽然它不能保证。从3.7.2 / 2 [basic.stc.thread]:

The standard allows for this behavior, although it doesn't guarantee it. From 3.7.2/2 [basic.stc.thread]:

(例如在程序启动时)构建对象,因为第一次使用之前意味着在任何时间点,只要它在之前而不是刚好在之前。

It's also possible that the objects are constructed at some other time (e.g. on program startup), as "before first use" means "at any point as long as it is before" rather than does "just before".

这篇关于什么时候是一个`thread_local`全局变量初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:38