std::thread_local

std::thread_local是线程局部存储。每个线程都有一个对应备份,被std::thread_local修饰的变量生存周期和所属线程一致,线程被销毁该变量释放。

可以用以下代码观察:

#include<iostream>
#include<thread>

using namespace std;

thread_local int tcount = 0;
int flag = 1;

void fThread() {
    tcount++;
    cout << tcount << endl;
    while (flag) {
        ;
    }
}

int main()
{
    thread t1(fThread);
    thread t2(fThread);
    t1.join();
    t2.join();
    return 0;
}

程序输出的结果是:

1

1

原文地址:https://www.cnblogs.com/HadesBlog/p/13701280.html