C++11特性——thread_local

  C++11引入thread_local来保证线程安全,这篇文章主要介绍下thread_local的基本知识。主要围绕以下四个主题:
  1.thread_local基本介绍
  2.为什么要thread_local?
  3.什么时候用thread_local?
  4.thread_local使用

一、基本介绍

  thread_local是C++11引入的新特性,是一个关键字,用于修饰变量。
  在使用时需要加入头文件:#include< thread>
  thread_local关键字和static、extern关键字在使用上是不冲突的,例如:thread_local static a;

二、为什么要thread_local

  在多线程操作中,对于公共区域(比如全局变量)的访问可能存在问题,如果发生错乱,那么变量的值就不可预测,此时称线程不安全。thread_local就是用来保证线程安全的。

三、什么时候用thread_local

  thread_local的目的是防止变量值的不可预测性,保证各线程内变量值的互不干扰。有两种情况是不需要thread_local的:
  1)变量仅仅作为局部变量使用,即使是多线程情况下执行函数的时候各线程会在栈空间内分配空间来实现变量间的隔离
  2)多线程中的共享变量,也就是进程级别,像全局的资源计数器

  排除以上两种情况,thread_local就是达到线程内独有的全局变量,有一些常见的使用场景:
  1)生成随机数
  2)线程池

四、thread_local的使用

  thread_local主要是用来修饰变量,修饰变量的种类有以下四种:
  1)全局变量
  2)局部变量
  3)类对象
  4)类成员变量

  谈到变量,就会有变量的作用域和生存域。作用域没什么影响,全局变量作用全局,局部变量以函数为作用域。但thread_local修饰过的变量,变量的生存周期不再以程序为准,而是以线程生命周期,thread_local声明的变量存储在线程开始时分配,线程结束时销毁。每一个thread_local变量在线程中有独立实体,各变量间互相不干扰。关于thread_local修饰变量生存域问题可以看看这篇文章:深入理解c++11thread_local_南城小馆的博客-CSDN博客
  再来想想thread_local实现变量隔离的原理,其实是为每个线程创建线程本地数据(也叫线程局部数据),线程局部数据专属于线程。在线程内是共享,线程间独立。本质上,就相当于线程域的全局静态变量。
  详细的看看修饰的变量种类,可划分为两大类:一种和class类有关,一种和class类无关。和class类有关在线程结束时,会调用class的析构函数。
  如果在类的成员函数内定义了 thread_local 变量,则对于同一个线程内的该类的多个对象都会共享一个变量实例,并且只会在第一次执行这个成员函数时初始化这个变量实例,这一点是跟类的静态成员变量是相似的。
  当使用thread_local描述类成员变量时,必须是static的。传统的static类成员变量是所有对象共享,而static thread_local修饰的时候会变成在线程内共享,线程间不是共享的(对象可能来自同一线程,可能来自多个线程)

  在多线程领域,一个常见的问题的是否加锁?thread_local是不需要锁的。使用了thread_local之后,就将这一种单个线程生命周期内使用的场景隔离开来了,这种变量本来就不需要与其他线程共享这部分数据,所以也不需要加锁

  过程中看到一个概念是线程本地存储:thread local storage(简称TLS)。也叫线程特有存储。在此没有深入了解,实质上是线程私有的全局变量。多线程编程的环境中给全局或静态的变量每个线程分配不同的存储空间互不干扰

  下面从代码的角度来看看thread_local在四种情况下的使用:
  全局变量

#include <iostream>
#include <mutex>
#include <thread>
std::mutex cout_mutex;    //方便多线程打印, 加锁只是为了方便多线程打印

thread_local int x = 1;

void thread_func(const std::string&thread_name){
    for(int i = 0; i < 3; i++){
        x++;
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << "thread[" << thread_name << "]: x = " << x << std::endl;
    }
}

int main() {
    std::thread t1(thread_func, "t1");
    std::thread t2(thread_func, "t2");
    t1.join();
    t2.join();
    return 0;
}

  结果:
在这里插入图片描述
  局部变量

#include <iostream>
#include <mutex>
#include <thread>
std::mutex cout_mutex;    //方便多线程打印

void thread_func(const std::string& thread_name) {
    for (int i = 0; i < 3; ++i) {
        thread_local  int x = 1;  //只在每个线程创建时初始化一次
        x++;
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << "thread[" << thread_name << "]: x = " << x << std::endl;
    }
}

int main() {
    std::thread t1(thread_func, "t1");
    std::thread t2(thread_func, "t2");
    t1.join();
    t2.join();
    return 0;
}

  结果:
在这里插入图片描述
  类对象

#include <iostream>
#include <mutex>
#include <thread>
std::mutex cout_mutex;    //方便多线程打印

class A{
public:
    A(){
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << "create A" << std::endl;
    }

    ~A() {
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << "destroy A" << std::endl;
    }

    int counter = 0;
    int get_value() {
        return counter++;
    }
};

void thread_func(const std::string& thread_name) {
    for (int i = 0; i < 3; ++i) {
        thread_local A* a = new A();
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << "thread[" << thread_name << "]: a.counter:" << a->get_value() << std::endl;
    }
    return;
}

int main() {
    std::thread t1(thread_func, "t1");
    std::thread t2(thread_func, "t2");
    t1.join();
    t2.join();
    return 0;
}

  结果:
在这里插入图片描述
  类成员变量

#include <iostream>
#include <mutex>
#include <thread>
std::mutex cout_mutex;    //方便多线程打印


class B {
public:
    B() {
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << "create B" << std::endl;
    }
    ~B() {
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << "destroy B" << std::endl;
    }
    thread_local static int b_key;
    //thread_local int b_key;
    int b_value = 24;
    static int b_static;
};
thread_local int B::b_key = 12; // static数据要在外部初始化
int B::b_static = 36;
void thread_func(const std::string& thread_name) {
    B b;
    for (int i = 0; i < 3; ++i) {
        b.b_key--;
        b.b_value--;
        B::b_static--;   // not thread safe
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << "thread[" << thread_name << "]: b_key:" << b.b_key << ", b_value:" << b.b_value << ", b_static:" << b.b_static << std::endl;
        std::cout << "thread[" << thread_name << "]: B::key:" << B::b_key << ", b_value:" << b.b_value << ", b_static: " << B::b_static << std::endl;
    }
    return;
}

int main() {
    std::thread t1(thread_func, "t1");
    std::thread t2(thread_func, "t2");
    t1.join();
    t2.join();
    return 0;
}

  结果:
在这里插入图片描述
代码参考:C/C++编程:thread_local 用法_OceanStar的学习笔记的博客-CSDN博客

因作者水平有限,如有错误之处,请在下方评论区指正,谢谢!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值