天天看點

C++ thread_local變量初始化

C++ thread_local變量在什麼時候初始化,如果線程裡面沒有用到這個變量,變量是否還會被初始化?

為了驗證這個問題,先寫了一個類,constructor和destructor的時候,都列印一些資訊。

class MyNewClass {
    public:
    MyNewClass() {
        cout << "constructor" << endl;
    }
    ~MyNewClass() {
        cout << "destructor" << endl;
    }
    void hello() {
        return;
    }
};           
C++ thread_local變量初始化

Test Class

然後定義thread_local變量,用于thread。

thread_local MyNewClass m;

void my_thread_func(const std::string& name) {
    int my = 0;
    cout << "before in the loop" << endl;
    while(my < 3) {
        using namespace std::chrono_literals;
        m.hello();
        my++;
        std::this_thread::sleep_for(2000ms);
    }
    cout << "after the loop" << endl;
}

int main() {
    string name_a = "a";
    string name_b = "b";
    std::thread my_thread_a(my_thread_func, name_a), my_thread_b(my_thread_func, name_b);
    my_thread_a.join();
    my_thread_b.join();
    cout << "After join" << endl;
    return 0;
}           
C++ thread_local變量初始化

代碼

運作結果如下:

C++ thread_local變量初始化

運作結果

可以看到,線上程建立的時候,這個thread_local對象還沒有初始化。直到使用的時候,constructor才會被調用。

但是可以看到,主線程一直都沒有調用constructor。

在主程式裡面添加對thread_local對象的使用。

C++ thread_local變量初始化

main thread

輸出結果:

C++ thread_local變量初始化

main thread output

可以看到,這個時候主程式裡面的thread_local對象才會被初始化。而且隻有在用到的時候才會被初始化。

繼續閱讀