美食网站 源码,网站制作咨询,wordpress 登录失败,微信推广方案C之thread_local变量_c threadlocal-CSDN博客
thread_local简介 thread_local 是 C11 为线程安全引进的变量声明符。表示对象的生命周期属于线程存储期。 线程局部存储(Thread Local Storage#xff0c;TLS)是一种存储期(storage duration)#xff0c;对象的存储是在…C之thread_local变量_c threadlocal-CSDN博客
thread_local简介 thread_local 是 C11 为线程安全引进的变量声明符。表示对象的生命周期属于线程存储期。 线程局部存储(Thread Local StorageTLS)是一种存储期(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_guardstd::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 是静态存储周期就没有这个特性两个线程互相产生了影响。 —————————————