C++11 关键字thread_local

2022/5/5 17:12:51

本文主要是介绍C++11 关键字thread_local,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

C++11新增的关键字thread_local,表示对象的生命周期属于线程存储期。


如果类的成员函数内定义了 thread_local 变量,则对于同一个线程内的该类的多个对象都会共享一个变量实例,并且只会在第一次执行这个成员函数时初始化这个变量实例。


thread_local 一般用于需要保证线程安全的函数中。

使用场景:

随机数生成,每个线程维护不同的种子。

线程池,观察每个线程的负载情况。


本质上,就是线程域的全局静态变量。


#include <iostream>
#include <string>
#include <thread>
#include <mutex>
 
thread_local unsigned int rage = 1; 
std::mutex cout_mutex;
 
void increase_rage(const std::string& thread_name){
    ++rage; // modifying outside a lock is okay; this is a thread-local variable
    std::lock_guard<std::mutex> lock(cout_mutex);
    std::cout << "Rage counter for " << thread_name << ": " << rage << '\n';
}
 
int main(){
    std::thread a(increase_rage, "a"), b(increase_rage, "b");
 
    {
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << "Rage counter for main: " << rage << '\n';
    }
 
    a.join();
    b.join();
}

可以看出,主线程、线程a、线程b对变量rage的访问都是独立的。



这篇关于C++11 关键字thread_local的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程