????????thread_local是C++11为了线程安全引入的变量声明符,跟gcc内置的线程局部存储设备__thread功能类似。thread_local声明的对象的存储在每个线程开始时分配,在线程结束是销毁。每一个thread_local变量在每个线程有一份独立实体,各个线程的变量互不干扰。
????????__thread只能用于修饰POD类型,不能修饰class类型因为无法自动调用构造函数和析构函数,而thread_local可以修饰class类型,在线程结束时,会调用class的析构函数。
例:
#include <iostream>
#include <thread>
class Test1
{
public:
Test1(int _id):id(_id){}
~Test1(){ std::cout << "del t: " << std::this_thread::get_id() << " Id: " << getId() << std::endl; }
const int getId() const { return id; }
void setId(int val) { id = val; }
void add() { id++; }
void add(int val) { id += val; }
private:
int id;
};
thread_local int tVal = 1;
thread_local Test1 tClass(1);
void mainFunc()
{
tVal++;
tClass.add();
std::cout << "main: " << std::this_thread::get_id() << " tVal:" << tVal <<" tClass.Id: "<< tClass.getId()<<std::endl;
}
void Func1(const std::string&thread_name)
{
tVal += 10;
tClass.add(10);
std::cout << thread_name.c_str() <<": " << std::this_thread::get_id() << " tVal: " << tVal << " tClass.Id: " << tClass.getId() << std::endl;
}
void Func2(const std::string&thread_name)
{
tVal += 20;
tClass.add(20);
std::cout << thread_name.c_str() << ": " << std::this_thread::get_id() << " tVal:" << tVal << " tClass.Id: " << tClass.getId() << std::endl;
}
int main()
{
mainFunc();
std::thread t1(Func1,"t1");
std::thread t2(Func2, "t2");
t1.join();
t2.join();
mainFunc();
std::thread t3([=]()
{
tVal += 30;
tClass.add(30);
std::cout << "t3: " << std::this_thread::get_id() << " tVal:" << tVal << " tClass.Id: " << tClass.getId() << std::endl;
});
t3.join();
mainFunc();
return 0;
}
运行结果:
?
|