所谓线程独立局部存储,说白了,就是不同线程之间的变量独占内存空间,不共享,即便是全局变量
关键字 thread_local,不必纠结怎么实现的,会用就行
#include <windows.h>
#include <cstdio>
#include <iostream>
#include <thread>
#include <atomic>
using namespace std;
int thread_local g_nCount = 0; //情况1
//int g_nCount = 0;//情况2
void func0(int nArg1,int nArg2) {
g_nCount = 10;
for (auto i = 0; i < 10; ++i)
{
Sleep(10);
cout << "func0:" << &g_nCount << endl;
}
}
void func1() {
g_nCount = 11;
for (auto i = 0; i < 10; ++i) {
Sleep(10);
cout << "func1:" << &g_nCount << endl;
}
}
int main() {
thread t0(func0, 1, 2);
thread t1(func1);
t0.join();
t1.join();
//cout << g_stCount.nCount << endl;
system("pause");
return 0;
}
只要对比全局变量g_nCount两种不同情况的定义形式,查看运行结果,也能分析出,加了thread_local的情况下,变量数据在不同线程中,独立享有内存空间,即便定义的是全局变量,也是属于线程内的全局变量