C++ 11 关键字:thread_local(关键字在多线程无锁编程中很有用)

一、C++的存储周期

C++ 中有 4 种存储周期:

automatic : automatic就是栈和临时对象之类的
static   : static就是全局变量和static变量之类的;
dynamic  :dynamic就是heap上的,通过new出来的
thread_local thread_local就是Thread Local Storage,线程局部存储

二、thread_local 原理解释

  • 原理
    有且只有 thread_local 关键字修饰的变量具有线程(thread)周期,这些变量在线程开始的时候被生成,在线程结束的时候被销毁,并且每一个线程都拥有一个独立的变量实例

  • 使用条件
    thread_local 一般用于需要保证线程安全的函数中。

  • 初始化时机(跟static类似)
    需要注意的一点是,如果类的成员函数内定义了 thread_local 变量,则对于同一个线程内的该类的多个对象都会共享一个变量实例,并且只会在第一次执行这个成员函数时初始化这个变量实例,这一点是跟类的静态成员变量类似的。

三、测试案例

1)测试案例一

  • 测试代码
class A {
 public:
  A() {}
  ~A() {}

  void test(const std::string &name) {
    thread_local int count = 0;
    ++count;
    std::cout << name << ": " <<  count << std::endl;
  }
};

void func(const std::string &name) {
  A a1;
  a1.test(name);
  a1.test(name);
  A a2;
  a2.test(name);
  a2.test(name);
}

int main(int argc, char* argv[]) {
  std::thread t1(func, "t1");
  t1.join();
  std::thread t2(func, "t2");
  t2.join();
  return 0;
}
  • 测试结果展示
t1: 1
t1: 2
t1: 3
t1: 4
t2: 1
t2: 2
t2: 3
t2: 4

2)测试案例二(这里用的static与上面thread_local的做对比)

  • 测试代码
class A {
 public:
  A() {}
  ~A() {}

  void test(const std::string &name) {
    static int count = 0;
    ++count;
    std::cout << name << ": " <<  count << std::endl;
  }
};

void func(const std::string &name) {
  A a1;
  a1.test(name);
  a1.test(name);
  A a2;
  a2.test(name);
  a2.test(name);
}

int main(int argc, char* argv[]) {
  std::thread t1(func, "t1");
  t1.join();
  std::thread t2(func, "t2");
  t2.join();
  return 0;
}
  • 测试结果
t1: 1
t1: 2
t1: 3
t1: 4
t2: 5
t2: 6
t2: 7
t2: 8
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值