thread_local 线程本地变量
- 需要在可访问的作用域中声明
- 声明时可以初始化,但只有在线程中被使用时才实例化,随线程销毁时销毁
#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <string_view>
class Cls_A
{
int data;
public:
Cls_A(const int x):data{x}
{
std::cout << "Cls_A construct in thread:" << std::this_thread::get_id()<<" and data is "<< data << std::endl;
}
~Cls_A()
{
std::cout << "Cls_A destruct in thread:" << std::this_thread::get_id() <<std::endl;
}
void add()
{
++data;
}
int get() const
{
return data;
}
};
thread_local Cls_A x{21};
std::mutex mtx;
void func_0()
{
std::lock_guard<std::mutex> lock(mtx);
x.add();
std::cout << "thread:" << std::this_thread::get_id() << "'s x is " << x.get() << std::endl;
}
int main()
{
std::cout << x.get() << std::endl;
std::thread t1{func_0};
std::thread t2{func_0};
t1.join();
t2.join();
return 0;
}
|