C++ __thread的个人理解

C++ __thread的个人理解


前言

今天依然在调试我那个简陋的server,下午起床逛GitHub时候发现一个大佬在创建线程pthread时,先声明了个__thread,就像这样
在这里插入图片描述
我?这是啥玩意,找了度娘发现讲解的人也很少,于是对着一两篇现有文章记录下自己的理解


__thread

被__thread修饰的变量,在多线程中不是共享的而是每个线程单独一个,个人理解就是同一个变量即使多个线程同时调用,在同样的动作下也应该出现同样的一个结果。
既然一份变量,那就用static声明一下,验证即使static依旧可以满足前面的论述。
参考其他博客,发现说这个__thread之能用于修饰int等内置变量,对于类只能修饰没有自定义构造函数和析构函数的,如果有就需要通过类指针来修饰。


验证代码

#include<iostream>
#include<vector>
#include<pthread.h>
#include <unistd.h>
using namespace std;

class TestThread1{
public:
    char c;
    int i;
};

class TestThread2{
public:
    char c;
    int i;
    TestThread2(char _c,int _i):c(_c),i(_i){}
};

static __thread  int ti;
static __thread  TestThread1 t1;
static __thread  TestThread2* t2;

void* cbFunc1(void* arg){
    sleep(1);
    ti++;
    t1.c='c';
    t1.i=1;
    cout<<"ti: "<<ti<<" t1.c: "<<t1.c<<" t1.i: "<<t1.i<<endl;
    return NULL;
}
void* cbFunc2(void* arg){
    sleep(2);
    ti++;
    t2=new TestThread2('b',2);
    cout<<"ti: "<<ti<<" t2->c: "<<t2->c<<" t2->i: "<<t2->i<<endl;
    return NULL;
}

int main(){
    ti++;
    t1.c='m';
    t1.i=10;
    t2=new TestThread2('n',20);
    cout<<"(main)ti: "<<ti<<" t1.c: "<<t1.c<<" t1.i: "<<t1.i<<endl;
    cout<<"(main)ti: "<<ti<<" t2->c: "<<t2->c<<" t2->i: "<<t2->i<<endl;
    pthread_t p1,p2;
    pthread_create(&p1,NULL,cbFunc1,NULL);
    pthread_create(&p2,NULL,cbFunc2,NULL);
    pthread_join(p1,NULL);
    pthread_join(p2,NULL);

    cout<<"(main)ti: "<<ti<<" t1.c: "<<t1.c<<" t1.i: "<<t1.i<<endl;
    cout<<"(main)ti: "<<ti<<" t2->c: "<<t2->c<<" t2->i: "<<t2->i<<endl;
    return 0;
}

结果如下:
在这里插入图片描述
可以看到,对于同一个变量t1,自加了多次,大家的结果都一样,类里面的变量也是如此,每个线程对其作出的改变并没有影响其他线程。

而把__thread去掉,结果就成了
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

VioletEvergarden丶

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

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

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

打赏作者

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

抵扣说明:

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

余额充值