c++简单封装thread多线程操作

#include <iostream>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
using namespace std;
class Thread{
    public:
        Thread(){

        }
    private:
        pthread_t thread[10];
        int tail = 0;
        int ret = 0;
    public:
        //一个是要执行的函数,另一个是要执行的函数参数
        void thread_create(void *(*start_routine)(void *),void *arg);
        void show_thread_num();
        void thread_wait();


};

void Thread::thread_create(void *(*start_routine)(void *),void *arg){
    //先不要参数吧
    
    ret = pthread_create(&thread[tail++],NULL,*start_routine,NULL);
    if(ret == 0){
        printf("create thread success\n");
    }
    
}

void Thread::show_thread_num(){
    cout << tail  << endl;
}

void Thread::thread_wait() {
    for (int i = 0; i < tail; ++i) {
        pthread_join(thread[i],NULL);

    }
}

//定义一个线程函数  函数名就是地址
void *thrd_func_1(void *){
    printf("i am thread1\n");
    return NULL;
}
void *thrd_func_2(void *){
    sleep(10);
    printf("i am thread2\n");

    return NULL;
}
void *thrd_func_3(void *){
    printf("i am thread3\n");
    return NULL;
}

int main() {
    Thread a;
    a.thread_create(thrd_func_1,NULL);
    a.thread_create(thrd_func_2,NULL);
    a.thread_create(thrd_func_3,NULL);
    a.show_thread_num();
    a.thread_wait();

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值