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
", i);
    }
    int i = 0;
};

//thread_local S gs;
S gs;

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

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

本人微信:xiaoshitou5854

原文地址:https://www.cnblogs.com/xiaoshiwang/p/9892805.html