zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Java类加载机制
    Java内存模型
    遍历集合的常见方式,排序,用lambda表示是怎样的
    包和访问权限修饰符,.单例设计模式,.Object类常用方法,.内部类
    接口
    继承
    面向对象的四大特征 封装 继承 多态 抽象
    面向对象
    二维数组及Arrays工具类
    数组(冒泡,选择,排序)
  • 原文地址:https://www.cnblogs.com/xiaoshiwang/p/9892805.html
Copyright © 2011-2022 走看看