栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++中使用多线程

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++中使用多线程

通过pthread_create创建线程,然后将类函数通过函数指针的方式传入,在将Student类传参传入线程函数。编译时用g++ main.c -o main -std=c++11 -lpthread ,线程间可以通过指针进行数据共享。

#include
#include
#include
#include
#include //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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/352996.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号