#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;
}
c++简单封装thread多线程操作
最新推荐文章于 2024-04-24 21:51:47 发布