当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c/c++ 多线程 thread_local 类型

c/c++ 多线程 thread_local 类型

2018年11月03日  | 移动技术网IT编程  | 我要评论

合肥中山医院叶凡,山西万荣事件真相,色欲之死 完整版

多线程 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=%d\n", i);
    }
    int i = 0;
};

//thread_local s gs;
s gs;

void foo()
{
  gs.i += 1;
  printf("foo  %p, %d\n", &gs, gs.i);
}

void bar()
{   
  gs.i += 2;
  printf("bar  %p, %d\n", &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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网