网站上传后打不开网络seo营销推广
C++之thread_local变量_c++ threadlocal-CSDN博客
thread_local简介
thread_local 是 C++11 为线程安全引进的变量声明符。表示对象的生命周期属于线程存储期。
线程局部存储(Thread Local Storage,TLS)是一种存储期(storage duration),对象的存储是在线程开始时分配,线程结束时回收,每个线程有该对象自己的实例;如果类的成员函数内定义了 thread_local 变量,则对于同一个线程内的该类的多个对象都会共享一个变量实例,并且只会在第一次执行这个成员函数时初始化这个变量实例。
thread_local 一般用于需要保证线程安全的函数中。本质上,就是线程域的全局静态变量。
———————————
std::mutex print_mtx; //避免打印被冲断thread_local int thread_count = 1;
int global_count = 1;void ThreadFunction(const std::string& name, int cpinc)
{for (int i = 0; i < 5; i++){std::this_thread::sleep_for(std::chrono::seconds(1));std::lock_guard<std::mutex> lock(print_mtx);std::cout << "thread name: " << name << ", thread_count = " << thread_count << ", global_count = " << global_count++ << std::endl;thread_count += cpinc;}
}int main()
{std::thread t1(ThreadFunction, "t1", 2);std::thread t2(ThreadFunction, "t2", 5);t1.join();t2.join();
}输出:thread name: t2, thread_count = 1, global_count = 1
thread name: t1, thread_count = 1, global_count = 2
thread name: t1, thread_count = 3, global_count = 3
thread name: t2, thread_count = 6, global_count = 4
thread name: t1, thread_count = 5, global_count = 5
thread name: t2, thread_count = 11, global_count = 6
thread name: t1, thread_count = 7, global_count = 7
thread name: t2, thread_count = 16, global_count = 8
thread name: t1, thread_count = 9, global_count = 9
thread name: t2, thread_count = 21, global_count = 10
可以看出来每个线程中的 thread_count 都是从 1 开始打印,这印证了 thread_local 存储类型的变量会在线程开始时被初始化,每个线程都初始化自己的那份实例。另外,两个线程的打印数据也印证了 thread_count 的值在两个线程中互相不影响。作为对比的 global_count 是静态存储周期,就没有这个特性,两个线程互相产生了影响。
—————————————