线程一般没有自己的全局变量,C++11 引入了 thread_local 解决了这个问题。
示例
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <iostream>
#include <thread>
using namespace std;
thread_local int i = 0;
int func(int val){
i = val;
i = i + 2;
std::cout << i;
}
int func2(){
std::cout << i;
}
int main(){
i = 9;
std::thread t1(func,1);
std::thread t2(func,2);
std::thread t3(func,3);
std::thread t4(func2);
t1.join();
t2.join();
t3.join();
t4.join();
std::cout << i << std::endl;
return 0;
}
结果打印 53409。线程 t1,t2,t3,t4 是 4 个子线程,在每个线程中都独享一份 i,i 的初始值为 0,所以运算都是在这个基础上进行,打印出 5340。
参考
http://trickness.github.io/morden%20c++/2015/09/26/C++11&14-thread_local/
http://en.cppreference.com/w/cpp/language/storage_duration