c++中使用多线程

这篇博客介绍了如何在C++中利用pthread库创建线程,并通过函数指针传递类成员函数作为线程入口。示例展示了线程间如何共享和修改`Student`类的`age`属性,通过`pthread_create`创建两个线程,分别调用`playgameF`和`dohomeworkF`函数,这两个函数会并发地更新对象的年龄并打印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值