请用C++写一个线程池程序,并注释
时间: 2023-03-07 19:33:46 浏览: 98
//线程池程序:
#include <stdio.h>
#include <pthread.h>
//定义线程池结构体
typedef struct{
void* (*run)(void* args);//函数指针,回调函数
void* args;//回调函数的参数
pthread_t tid;//线程id
int status;//状态
int pool_num;//线程池中线程的数量
}threadpool_t;
//初始化线程池
void threadpool_init(threadpool_t* pool, int pool_num){
pool->pool_num = pool_num;
pool->status = 0;
for(int i=0; i<pool_num; i++){
pthread_create(&(pool->tid), NULL, pool->run, pool->args);//创建线程
}
pool->status = 1;
}
//销毁线程池
void threadpool_destroy(threadpool_t* pool){
pool->status = 0;
for(int i=0; i<pool->pool_num; i++){
pthread_join(pool->tid, NULL);//等待线程结束
}
pool->pool_num = 0;
}
阅读全文