多线程 thread_local 类型
thread_local变量是c++ 11新引入的一种存储类型。
- thread_local关键字修饰的变量具有线程周期(thread duration),
- 这些变量(或者说对象)在线程开始的时候被生成(allocated),
- 在线程结束的时候被销毁(deallocated)。
- 并且每 一个线程都拥有一个独立的变量实例(each thread has its own instance of the object)。
thread_local
可以和static
与extern
关键字联合使用,这将影响变量的链接属性(to adjust linkage)。
例子:
#include <iostream> #include <thread> struct s { s() { printf("s() called i=%dn", i); } int i = 0; }; //thread_local s gs; s gs; void foo() { gs.i += 1; printf("foo %p, %dn", &gs, gs.i); } void bar() { gs.i += 2; printf("bar %p, %dn", &gs, gs.i); } int main() { std::thread a(foo), b(bar); a.join(); b.join(); }
执行结果:结构体s只生成了一个对象实例,并且2个线程是共享这个实例的,可以看出实例的内存地址相同
s() called i=0 bar 0x55879165501c, 2 foo 0x55879165501c, 3
如果把:s gs;加上thread_local关键字,
thread_local s gs;
执行结果:结构体s在每个线程中都生成了一个实例,可以看出实例的内存地址不相同。
s() called i=0 bar 0x7f23eb2506f8, 2 s() called i=0 foo 0x7f23eba516f8, 1
c/c++ 学习互助qq群:877684253
本人微信:xiaoshitou5854
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/606491.html