通过pthread_create创建线程,然后将类函数通过函数指针的方式传入,在将Student类传参传入线程函数。编译时用g++ main.c -o main -std=c++11 -lpthread ,线程间可以通过指针进行数据共享。
#include <pthread.h>
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <unistd.h>//sleep需要
using namespace std;
void* playgameF(void* param);
void* dohomeworkF(void* param);
class Student{
public:
Student(){
this->playgame = playgameF;//初始化线程入口函数指针
this->dohomework = dohomeworkF;//初始化线程入口函数指针
}
void* (*dohomework)(void* param);//线程入口函数1指针
void* (*playgame)(void* param);//入口函数2指针
// int age =100;
int getAge(){
return age;
}
void setAge(){
age++;
}
private:
int age = 100;
};
void* playgameF(void* param){
while(1){
cout << "11111" << endl;
////在线程中修改student实例的age值并且打印出来
((Student*)param)->setAge();//
cout << ((Student*)param)->getAge() << endl;
sleep(1);
}
int* a = (int*)calloc(1,sizeof(int));
*a = 10;
cout << *a << endl;
return (void*)a;
}
void* dohomeworkF(void* param){
int a = 0;
while(1){
cout << "22222" << endl;
((Student*)param)->setAge();
cout << ((Student*)param)->getAge() << endl;
sleep(10);
}
}
int main(int argc, char* argv[]){
Student stu1;
int return_vuale = 0;//返回值测试,没有成功
// int* return_ptr = &return_ptr;
pthread_t prt_id1;//线程1 id
pthread_t prt_id2;//线程2 id
//int a = 9;
void* param = (void*)&stu1;//将stu1转为void指针进行传参
pthread_create(&prt_id1, NULL, stu1.playgame, param);//创建线程
pthread_create(&prt_id2, NULL, stu1.dohomework, param);//同上
pthread_join(prt_id1, (void **)&return_vuale);//设置返回值,失败了的,这一段可以注释
cout << "return = " << return_vuale << endl;//可以注释
// while(1){}
//cout << a << endl;
pthread_exit(NULL);//等待着线程都退出了主线程才退出
return 0;
}