C++11 关键字 thread_local

thread_local 线程本地变量

  1. 需要在可访问的作用域中声明
  2. 声明时可以初始化,但只有在线程中被使用时才实例化,随线程销毁时销毁
#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <string_view>

class Cls_A
{
    int data;
public:
    Cls_A(const int x):data{x}
    {
        std::cout << "Cls_A construct in thread:" << std::this_thread::get_id()<<" and data is "<< data << std::endl;
    }
    ~Cls_A()
    {
        std::cout << "Cls_A destruct in thread:" << std::this_thread::get_id() <<std::endl;
    }
    void add()
    {
        ++data;
    }
    int get() const
    {
        return data;
    }
};

thread_local Cls_A x{21};

std::mutex mtx;

void func_0()
{
    std::lock_guard<std::mutex> lock(mtx);
    x.add();
    std::cout << "thread:" << std::this_thread::get_id() << "'s x is " << x.get() << std::endl;
}

int main()
{
    std::cout << x.get() << std::endl;
    std::thread t1{func_0};
    std::thread t2{func_0};
    t1.join();
    t2.join();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tadus_zeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值