1. __thread 关键字表示每一个线程有一份独立的实体,每一个线程都不会干扰。
2. __thread 只能修饰POD变量,简单的来说可以是如下几种变量
(1) 基本类型 (int , float 等等)
(2)指针类型
(3) 不带自定义构造函数和析构函数的类,如果希望修饰带自定义构造和析构函数的类,需要用到指针。
3. 实验代码
(1)__thread 可以修饰stu_t, 因为stu_t没有自定义的构造和析构函数
(2)__thread 可以修饰teacher_t*,因为__thread可以修饰指针
(3)实验结果表示在不同的线程中,变量不会相互影响。
#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <string>
class stu_t {
public:
int num;
int age;
};
class teacher_t {
public:
int num;
int age;
teacher_t (int num, int age) {
this->num = num;
this->age = age;
}
};
static __thread int count;
static __thread stu_t stu;
static __thread teacher_t* teacher;
void print(std::string description, int num, stu_t stu, teacher_t* teacher) {
std::cout << description << ", before======>" << "pid:" << getpid() << ", pthread id:" << pthread_self() << ", count:" << count << std::endl;
std::cout << description << ", before======>" << "pid:" << getpid() << ", pthread id:" << pthread_self() << ", snum:" << stu.num << ", sage:"<< stu.age << std::endl;
std::cout << description << ", before======>" << "pid:" << getpid() << ", pthread id:" << pthread_self() << ", snum:" << teacher->num << ", tage:"<< teacher->age << std::endl;
}
void *function1(void *argc)
{
count = 2;
stu.num = 2;
stu.age = 2;
teacher = new teacher_t(2,2);
sleep(1);
print("thread1", count, stu, teacher);
return 0;
}
void *function2(void *argc)
{
stu.num = 3;
stu.age = 3;
count = 3;
teacher = new teacher_t(3,3);
sleep(2);
print("thread2", count, stu, teacher);
return 0;
}
int main()
{
pthread_t thread_id[2];
int ret;
stu.num = 1;
stu.age = 1;
count = 1;
teacher = new teacher_t(1,1);
print("main", count, stu, teacher);
pthread_create(thread_id, NULL, function1, NULL);
pthread_create(thread_id + 1, NULL, function2, NULL);
pthread_join(thread_id[0], NULL);
pthread_join(thread_id[1], NULL);
print("main", count, stu, teacher);
return 0;
}
4. 实验结果
main, before======>pid:697, pthread id:0x7fff91ca0380, count:1
main, before======>pid:697, pthread id:0x7fff91ca0380, snum:1, sage:1
main, before======>pid:697, pthread id:0x7fff91ca0380, snum:1, tage:1
thread1, before======>pid:697, pthread id:0x700002525000, count:2
thread1, before======>pid:697, pthread id:0x700002525000, snum:2, sage:2
thread1, before======>pid:697, pthread id:0x700002525000, snum:2, tage:2
thread2, before======>pid:697, pthread id:0x7000025a8000, count:3
thread2, before======>pid:697, pthread id:0x7000025a8000, snum:3, sage:3
thread2, before======>pid:697, pthread id:0x7000025a8000, snum:3, tage:3
main, before======>pid:697, pthread id:0x7fff91ca0380, count:1
main, before======>pid:697, pthread id:0x7fff91ca0380, snum:1, sage:1
main, before======>pid:697, pthread id:0x7fff91ca0380, snum:1, tage:1