当前位置: 首页 > news >正文

C++之thread_local变量

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 是静态存储周期,就没有这个特性,两个线程互相产生了影响。
—————————————

http://www.lryc.cn/news/547931.html

相关文章:

  • 【国产Linux | 银河麒麟】麒麟化龙——KylinOS下载到安装一条龙服务,起飞!
  • (接“使用js去复制网页内容的方法”)js中的execCommand怎么复制富文本内容解析
  • npm ERR! code 128 npm ERR! An unknown git error occurred
  • 解决Leetcode第3470题全排列IV
  • MyBatis 配置文件核心
  • bert模型笔记
  • 微信小程序接入deepseek
  • 推荐算法和推荐系统入门第一趴
  • unity pico开发 四 物体交互 抓取 交互层级
  • 基于深度学习的青花瓷图像检索系统开发与实现
  • uniapp 系统学习,从入门到实战(八)—— Vuex 的使用
  • Vue Hooks 深度解析:从原理到实践
  • django中序列化器serializer 的高级使用和需要注意的点
  • 靶场(二)---靶场心得小白分享
  • PHP Error处理指南
  • 视频输入设备-V4L2的开发流程简述
  • 【Manus资料合集】激活码内测渠道+《Manus Al:Agent应用的ChatGPT时刻》(附资源)
  • Mybatis集合嵌套查询,三级嵌套
  • thinkphp5.1 在fetch模版就超时
  • Dockerfile 深入浅出:从基础到进阶全解析
  • CAD2025电脑置要求
  • android App主题颜色动态更换
  • 微服务,服务治理nacos,负载均衡LOadBalancer,OpenFeign
  • 浅论数据库聚合:合理使用LambdaQueryWrapper和XML
  • FastGPT 引申:混合检索完整实例
  • Socket.IO聊天室
  • MySQL表中数据基本操作
  • 可狱可囚的爬虫系列课程 16:爬虫重试机制
  • 第十五届蓝桥杯----B组cpp----真题解析(小白版本)
  • 软考架构师笔记-数据库系统