![](/img/trans.png)
[英]When exactly is a thread_local variable declared at global scope initialized?
[英]When is a `thread_local` global variable initialized?
考慮以下示例(為簡單起見,省略了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
Constructor
10 次。 此外,clang 抱怨一個明顯的未使用的表達式結果。
由於thread_local
存儲生命周期應該跨越整個線程的生命周期,因此無論用戶輸入如何,我都希望在每個線程中初始化foo
變量。
我可能想要一個thread-local
變量,其唯一目的是在構造函數中產生副作用,標准是否要求在首次使用時初始化thread_local
對象?
該標准允許這種行為,盡管它不保證。 從 3.7.2/2 [basic.stc.thread]:
具有線程存儲持續時間的變量應在其第一次 odr 使用 (3.2) 之前初始化,並且如果構造,應在線程退出時銷毀。
也有可能在其他時間(例如在程序啟動時)構造對象,因為“首次使用之前”意味着“在任何時候只要它在之前”而不是“就在之前”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.