欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

thead_local修饰的变量

程序员文章站 2022-04-05 08:50:23
...

什么是thread_local

thread_local变量是c++11引入的一个新的存储类型,它将影响变量的生存期。

哪些变量可以用thread_local修饰

  1. 命名空间下的全局变量
  2. 类的静态成员变量
  3. 局部变量

thread_local修饰的变量的初始化过程与生存期

下面通过一个小例子观察thread_local修饰的变量的初始化过程与生存期

#include <iostream>
#include <string>
#include <thread>
using std::cout;
using std::endl;
class CustomeVariable
{
	
public:
	CustomeVariable(const char* name="zhangsan"):name_(name){
		std::cout << "name<" << name_ << ">," << "id<" << std::this_thread::get_id() << ">construct" << std::endl;
	}
	~CustomeVariable(){
		std::cout << "name<" << name_ << ">," << "id<" << std::this_thread::get_id() << ">destruct" << std::endl;
	}

	void setName(const std::string& name){
		name_ = name;
	}

	std::string getName() const{
		return name_;
	}
private:
	std::string name_; 
};

class Demo
{
	friend std::ostream&  print(std::ostream& os, Demo* ptr);
public:
	
private:
	static thread_local CustomeVariable custom_variable_;
};
std::ostream&  print(std::ostream& os, Demo* ptr)
{
	return os << ptr->custom_variable_.getName() << std::endl;
}

thread_local CustomeVariable Demo::custom_variable_;
int main()
{
	Demo demo;
	print(std::cout, &demo);
	std::thread t(print,std::ref(std::cout), &demo);
	system("pause");
    return 0;
}


结果如下:
thead_local修饰的变量
可以看出:
thread_local变量在线程启动后开始初始化,并在线程结束后销毁

相关标签: C++11