C++ 11 关键字:thread_local(转)

thread_local 是 C++ 11 新引入的一种存储类型,它会影响变量的存储周期。

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

automatic
static
dynamic
thread

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

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

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

注意:static thread_local与单独thread_local等价

下面用一些测试样例说明:
case 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

case 2:

复制代码
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

 

posted @   鸭子船长  阅读(664)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2020-07-07 海量数据面试题(附题解+方法总结)(转)
2020-07-07 leetcode刷题(六)路径总和I、II、III(转)
2020-07-07 浅谈AVL树,红黑树,B树,B+树原理及应用(转)
2020-07-07 [LeetCode] 860. Lemonade Change 买柠檬找零(转)
2020-07-07 [leetcode] 134. Gas Station 解题报告(转)
点击右上角即可分享
微信分享提示