前言
今天依然在调试我那个简陋的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去掉,结果就成了