c/c++ 多线程 thread_local 类型

多线程 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();
}
github源代码

执行结果:结构体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

1414315-20181101215147626-1192980080.jpg

本人微信:xiaoshitou5854

转载于:https://www.cnblogs.com/xiaoshiwang/p/9892805.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值