上一篇 (78条消息) C++ 基础12、线程池和有锁队列设计封装_Mr-zhou先生的博客-CSDN博客中讲述了关于使用 std::thread 创建线程池的方法,今天这一篇使用原始的创建线程方法来创建线程池
一、线程创建
主体,线程池初始创建传参数 最小线程数和最大线程数以及队列大小,其中队列大小使用数组表示,不在使用STL库中的容器
/**
* 线程池创建
* @brief createthreadPool
* @param min_thr_num
* @param max_thr_num
* @param max_queue_size
* @return
*/
threadPool_t * createthreadPool(int min_thr_num,int max_thr_num,int max_queue_size){
threadPool_t *pool = NULL;
do {
if(pool==nullptr){
if((pool = (threadPool_t*)malloc(sizeof (threadPool_t)))==nullptr)
{
std::cout<<"malloc thread pool failed"<<std::endl;
break;
}
}
/// 参数赋值
pool->min_thr_num = min_thr_num;
pool->max_thr_num = max_thr_num;
pool->queue_max_size = max_queue_size;
pool->live_thr_num = min_thr_num;
/// 参数校验
if((max_thr_num <=0) ||(max_thr_num < min_thr_num) || (max_queue_size <=0))
{
std::cout<<"createPool param value is invailed"<<std::endl;
break;
}
/// 线程 id 空间申请
if((pool->threads = (pthread_t*)malloc(sizeof (pthread_t)*max_thr_num))==nullptr){
std::cout<<"pool threads malloc failed "<<std::endl;
break;
}
else{
/// 线程id 清零
memset(pool->threads,0,sizeof(pthread_t)*max_thr_num);
/// 队列容器内存申请
pool->task_queue = (threadPool_task*)malloc(sizeof(threadPool_task)*max_queue_size);
if(pool->task_queue == nullptr){
std::cout<<"threadPool_task malloc failed "<<std::endl;
break;
}
/** 初始化互斥琐、条件变量 */
if (pthread_mutex_init(&(pool->lockself), NULL) != 0
|| pthread_mutex_init(&(pool->busy_thread_counter), NULL) != 0
|| pthread_cond_init(&(pool->queue_not_empty), NULL) != 0
|| pthread_cond_init(&(pool->queue_not_full), NULL) != 0)
{
std::cout<<"init the lock or cond fail"<<std::endl;
break;
}
/** 依据 最小线程数 进行创建**/
for(int i=0;i<pool->min_thr_num;i++){
pthread_create(&(pool->threads[i]),nullptr,threadpool_thread,(void*)pool);
std::cout<<"thread start"<<std::endl;
}
/** 启动管理者线程 */
pthread_create(&(pool->adjust_tid), NULL, adjust_thread, (void *)pool);
return pool;
}
} while (0);
threadpool_free(pool);
return nullptr;
}
二、工作线程
工作线程中任务队列中获取任务,并执行,在执行过程中并对线程进行动态管理。
/**
* 工作线程
* 从工作队列中获取任务的一种方法
* 动态性的线程分配管理
* @brief threadpool_thread
* @param threadpool
* @return
*/
void *threadpool_thread(void *threadpool){
threadPool_t *pool = (threadPool_t*)threadpool;
threadPool_task task;
while (true) {
pthread_mutex_lock(&pool->lockself);
/** 是否关闭线程池**/
if(pool->shutdown){
std::cout<<"thread shutdown"<<std::endl;
pthread_mutex_unlock(&pool->lockself);
pthread_exit(nullptr);
}
while (pool->queue_size ==0 && (!pool->shutdown)) {
/** 等待任务队列不为空**/
pthread_cond_wait(&(pool->queue_not_empty),&(pool->lockself));
/** 线程管理**/
if (pool->wait_exit_thr_num > 0) {
pool->wait_exit_thr_num--;
if(pool->live_thr_num>pool->min_thr_num){
pool->live_thr_num --;
pthread_mutex_unlock(&pool->lockself);
pthread_exit(nullptr);
}
}
}
/** 从队列头部获取工作**/
task.function = pool->task_queue[pool->queue_front].function;
task.arg = pool->task_queue[pool->queue_front].arg;
/** 更新 对头 下标 **/
pool->queue_front = (pool->queue_front+1) % pool->queue_max_size;
pool->queue_size--;
/** 通知可以有新的任务添加进来*/
pthread_cond_broadcast(&(pool->queue_not_full));
std::cout<<"2"<<std::endl;
pthread_mutex_unlock(&pool->lockself);
/** 执行任务 **/
pthread_mutex_lock(&(pool->busy_thread_counter));
pool->busy_thr_num++;
pthread_mutex_unlock(&(pool->busy_thread_counter));
(*(task.function))(task.arg);
/** 任务结束 **/
pthread_mutex_lock(&(pool->busy_thread_counter));
pool->busy_thr_num--;
pthread_mutex_unlock(&(pool->busy_thread_counter));
}
pthread_exit(nullptr);
}
三、线程管理
创建一个线程,对线程进行动态管理,创建线程或者销毁线程。
/** 管理线程 */
void *adjust_thread(void *threadpool)
{
int i;
threadPool_t *pool = (threadPool_t *)threadpool;
while (!pool->shutdown) {
Sleep(DEFAULT_TIME); /*定时 对线程池管理*/
pthread_mutex_lock(&(pool->lockself));
int queue_size = pool->queue_size; /* 关注 任务数 */
int live_thr_num = pool->live_thr_num; /* 存活 线程数 */
pthread_mutex_unlock(&(pool->lockself));
pthread_mutex_lock(&(pool->busy_thread_counter));
int busy_thr_num = pool->busy_thr_num; /* 忙着的线程数 */
pthread_mutex_unlock(&(pool->busy_thread_counter));
/* 创建新线程 算法: 任务数大于最小线程池个数, 且存活的线程数少于最大线程个数时 如:30>=10 && 40<100*/
if (queue_size >= MIN_WAIT_TASK_NUM && live_thr_num < pool->max_thr_num) {
pthread_mutex_lock(&(pool->lockself));
int add = 0;
/*一次增加 DEFAULT_THREAD 个线程*/
for (i = 0; i < pool->max_thr_num && add < DEFAULT_THREAD_VARY
&& pool->live_thr_num < pool->max_thr_num; i++) {
if (pool->threads[i] == 0 || !is_thread_alive(pool->threads[i])) {
pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool);
add++;
pool->live_thr_num++;
}
}
pthread_mutex_unlock(&(pool->lockself));
}
/* 销毁多余的空闲线程 算法:忙线程X2 小于 存活的线程数 且 存活的线程数 大于 最小线程数时*/
if ((busy_thr_num * 2) < live_thr_num && live_thr_num > pool->min_thr_num) {
/* 一次销毁DEFAULT_THREAD个线程, 隨機10個即可 */
pthread_mutex_lock(&(pool->lockself));
pool->wait_exit_thr_num = DEFAULT_THREAD_VARY; /* 要销毁的线程数 设置为10 */
pthread_mutex_unlock(&(pool->lockself));
for (i = 0; i < DEFAULT_THREAD_VARY; i++) {
/* 通知处在空闲状态的线程, 他们会自行终止*/
pthread_cond_signal(&(pool->queue_not_empty));
}
}
}
return NULL;
}
总体代码:
#include <thread>
#include <iostream>
#include <mutex>
#include <queue>
#include <atomic>
#include <condition_variable>
#include <string.h>
#include <QtGlobal>
#ifdef Q_OS_LINUX
#include <unistd.h>
#endif
#ifdef Q_OS_WIN32
#include <windows.h>
#endif
#define DEFAULT_TIME 1000 /*10s检测一次*/
#define MIN_WAIT_TASK_NUM 10 /*如果queue_size > MIN_WAIT_TASK_NUM 添加新的线程到线程池*/
#define DEFAULT_THREAD_VARY 10 /*每次创建和销毁线程的个数*/
/**
* 任务结构体
*/
typedef struct {
void *(*function)(void *);
void *arg;
}threadPool_task;
/**
* 线程池结构体信息
*/
struct threadPool_t{
threadPool_t(){
busy_thr_num = 0;
queue_size = 0;
queue_front = 0;
queue_rear = 0;
shutdown = false;
}
/** 用于琐住本身 **/
pthread_mutex_t lockself;
/** 忙状态线程锁 **/
pthread_mutex_t busy_thread_counter;
/** 队列不为空 **/
pthread_cond_t queue_not_empty;
/** 队列不满 **/
pthread_cond_t queue_not_full;
/** 线程 tid 数组 **/
pthread_t * threads;
/** 线程管理者 **/
pthread_t adjust_tid;
/** 任务队列 **/
threadPool_task *task_queue;
/** 线程池最小线程数 */
int min_thr_num;
/** 线程池最大线程数 */
int max_thr_num;
/** 当前存活线程个数 */
int live_thr_num;
/** 忙状态线程个数 */
int busy_thr_num;
/** 要销毁的线程个数 */
int wait_exit_thr_num;
/** task_queue队头下标 */
int queue_front;
/** task_queue队尾下标 */
int queue_rear;
/** task_queue队中实际任务数 */
int queue_size;
/** task_queue队列可容纳任务数上限 */
int queue_max_size;
/** 标志位,线程池使用状态,true或false */
int shutdown;
};
/**
* 释放内存
* @brief threadpool_free
* @param pool
*/
void threadpool_free(threadPool_t *pool){
if(pool ==nullptr)
return;
if(pool->task_queue){
free(pool->task_queue);
}
if(pool->threads){
free(pool->threads);
/** 释放前 先获取一下 **/
pthread_mutex_lock(&(pool->lockself));
pthread_mutex_destroy(&(pool->lockself));
pthread_mutex_lock(&(pool->busy_thread_counter));
pthread_mutex_destroy(&(pool->busy_thread_counter));
pthread_cond_destroy(&(pool->queue_not_empty));
pthread_cond_destroy(&(pool->queue_not_full));
}
free(pool);
pool =nullptr;
}
/**
* 工作线程
* 从工作队列中获取任务的一种方法
* 动态性的线程分配管理
* @brief threadpool_thread
* @param threadpool
* @return
*/
void *threadpool_thread(void *threadpool){
threadPool_t *pool = (threadPool_t*)threadpool;
threadPool_task task;
while (true) {
pthread_mutex_lock(&pool->lockself);
/** 是否关闭线程池**/
if(pool->shutdown){
std::cout<<"thread shutdown"<<std::endl;
pthread_mutex_unlock(&pool->lockself);
pthread_exit(nullptr);
}
while (pool->queue_size ==0 && (!pool->shutdown)) {
/** 等待任务队列不为空**/
pthread_cond_wait(&(pool->queue_not_empty),&(pool->lockself));
/** 线程管理**/
if (pool->wait_exit_thr_num > 0) {
pool->wait_exit_thr_num--;
if(pool->live_thr_num>pool->min_thr_num){
pool->live_thr_num --;
pthread_mutex_unlock(&pool->lockself);
pthread_exit(nullptr);
}
}
}
/** 从队列头部获取工作**/
task.function = pool->task_queue[pool->queue_front].function;
task.arg = pool->task_queue[pool->queue_front].arg;
/** 更新 对头 下标 **/
pool->queue_front = (pool->queue_front+1) % pool->queue_max_size;
pool->queue_size--;
/** 通知可以有新的任务添加进来*/
pthread_cond_broadcast(&(pool->queue_not_full));
std::cout<<"2"<<std::endl;
pthread_mutex_unlock(&pool->lockself);
/** 执行任务 **/
pthread_mutex_lock(&(pool->busy_thread_counter));
pool->busy_thr_num++;
pthread_mutex_unlock(&(pool->busy_thread_counter));
(*(task.function))(task.arg);
/** 任务结束 **/
pthread_mutex_lock(&(pool->busy_thread_counter));
pool->busy_thr_num--;
pthread_mutex_unlock(&(pool->busy_thread_counter));
}
pthread_exit(nullptr);
}
/**
* 任务添加
* @brief threadPool_add
* @param pool
* @param arg
*/
void threadPool_add(threadPool_t *pool,void*(*function)(void *arg),void*arg)
{
pthread_mutex_lock(&(pool->lockself));
if(pool->shutdown){
pthread_mutex_unlock(&(pool->lockself));
}
while((pool->queue_size == pool->queue_max_size) && (!pool->shutdown)){
pthread_cond_wait(&(pool->queue_not_full), &(pool->lockself));
}
/** 清空 工作线程 调用的回调函数 的参数arg */
if (pool->task_queue[pool->queue_rear].arg != NULL) {
free(pool->task_queue[pool->queue_rear].arg);
pool->task_queue[pool->queue_rear].arg = NULL;
}
/** 添加任务到任务队列里*/
pool->task_queue[pool->queue_rear].function = function;
pool->task_queue[pool->queue_rear].arg = arg;
pool->queue_rear = (pool->queue_rear + 1) % pool->queue_max_size; /* 队尾指针移动, 模拟环形 */
pool->queue_size++;
pthread_cond_signal(&(pool->queue_not_empty));
pthread_mutex_unlock(&(pool->lockself));
}
/**
*发0号信号,测试线程是否存活
* @brief is_thread_alive
* @param tid
* @return
*/
int is_thread_alive(pthread_t tid)
{
int kill_rc = pthread_kill(tid, 0);
if (kill_rc == ESRCH) {
return false;
}
return true;
}
/** 管理线程 */
void *adjust_thread(void *threadpool)
{
int i;
threadPool_t *pool = (threadPool_t *)threadpool;
while (!pool->shutdown) {
Sleep(DEFAULT_TIME); /*定时 对线程池管理*/
pthread_mutex_lock(&(pool->lockself));
int queue_size = pool->queue_size; /* 关注 任务数 */
int live_thr_num = pool->live_thr_num; /* 存活 线程数 */
pthread_mutex_unlock(&(pool->lockself));
pthread_mutex_lock(&(pool->busy_thread_counter));
int busy_thr_num = pool->busy_thr_num; /* 忙着的线程数 */
pthread_mutex_unlock(&(pool->busy_thread_counter));
/* 创建新线程 算法: 任务数大于最小线程池个数, 且存活的线程数少于最大线程个数时 如:30>=10 && 40<100*/
if (queue_size >= MIN_WAIT_TASK_NUM && live_thr_num < pool->max_thr_num) {
pthread_mutex_lock(&(pool->lockself));
int add = 0;
/*一次增加 DEFAULT_THREAD 个线程*/
for (i = 0; i < pool->max_thr_num && add < DEFAULT_THREAD_VARY
&& pool->live_thr_num < pool->max_thr_num; i++) {
if (pool->threads[i] == 0 || !is_thread_alive(pool->threads[i])) {
pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool);
add++;
pool->live_thr_num++;
}
}
pthread_mutex_unlock(&(pool->lockself));
}
/* 销毁多余的空闲线程 算法:忙线程X2 小于 存活的线程数 且 存活的线程数 大于 最小线程数时*/
if ((busy_thr_num * 2) < live_thr_num && live_thr_num > pool->min_thr_num) {
/* 一次销毁DEFAULT_THREAD个线程, 隨機10個即可 */
pthread_mutex_lock(&(pool->lockself));
pool->wait_exit_thr_num = DEFAULT_THREAD_VARY; /* 要销毁的线程数 设置为10 */
pthread_mutex_unlock(&(pool->lockself));
for (i = 0; i < DEFAULT_THREAD_VARY; i++) {
/* 通知处在空闲状态的线程, 他们会自行终止*/
pthread_cond_signal(&(pool->queue_not_empty));
}
}
}
return NULL;
}
int threadpool_destroy(threadPool_t *pool)
{
int i;
if (pool == NULL) {
return -1;
}
pool->shutdown = true;
/*先销毁管理线程*/
pthread_join(pool->adjust_tid, NULL);
for (i = 0; i < pool->live_thr_num; i++) {
/*通知所有的空闲线程*/
pthread_cond_broadcast(&(pool->queue_not_empty));
}
for (i = 0; i < pool->live_thr_num; i++) {
pthread_join(pool->threads[i], NULL);
}
threadpool_free(pool);
return 0;
}
/**
* 线程池创建
* @brief createthreadPool
* @param min_thr_num
* @param max_thr_num
* @param max_queue_size
* @return
*/
threadPool_t * createthreadPool(int min_thr_num,int max_thr_num,int max_queue_size){
threadPool_t *pool = NULL;
do {
if(pool==nullptr){
if((pool = (threadPool_t*)malloc(sizeof (threadPool_t)))==nullptr)
{
std::cout<<"malloc thread pool failed"<<std::endl;
break;
}
}
/// 参数赋值
pool->min_thr_num = min_thr_num;
pool->max_thr_num = max_thr_num;
pool->queue_max_size = max_queue_size;
pool->live_thr_num = min_thr_num;
/// 参数校验
if((max_thr_num <=0) ||(max_thr_num < min_thr_num) || (max_queue_size <=0))
{
std::cout<<"createPool param value is invailed"<<std::endl;
break;
}
/// 线程 id 空间申请
if((pool->threads = (pthread_t*)malloc(sizeof (pthread_t)*max_thr_num))==nullptr){
std::cout<<"pool threads malloc failed "<<std::endl;
break;
}
else{
/// 线程id 清零
memset(pool->threads,0,sizeof(pthread_t)*max_thr_num);
/// 队列容器内存申请
pool->task_queue = (threadPool_task*)malloc(sizeof(threadPool_task)*max_queue_size);
if(pool->task_queue == nullptr){
std::cout<<"threadPool_task malloc failed "<<std::endl;
break;
}
/** 初始化互斥琐、条件变量 */
if (pthread_mutex_init(&(pool->lockself), NULL) != 0
|| pthread_mutex_init(&(pool->busy_thread_counter), NULL) != 0
|| pthread_cond_init(&(pool->queue_not_empty), NULL) != 0
|| pthread_cond_init(&(pool->queue_not_full), NULL) != 0)
{
std::cout<<"init the lock or cond fail"<<std::endl;
break;
}
/** 依据 最小线程数 进行创建**/
for(int i=0;i<pool->min_thr_num;i++){
pthread_create(&(pool->threads[i]),nullptr,threadpool_thread,(void*)pool);
std::cout<<"thread start"<<std::endl;
}
/** 启动管理者线程 */
pthread_create(&(pool->adjust_tid), NULL, adjust_thread, (void *)pool);
return pool;
}
} while (0);
threadpool_free(pool);
return nullptr;
}
void *process(void *arg)
{
Sleep(1000);
std::cout<<"task is :"<<*(int *)arg<<std::endl;
return NULL;
}
int main(void)
{
std::cout<<"pool start"<<std::endl;
threadPool_t *thp = createthreadPool(3,100,100);/*创建线程池,池里最小3个线程,最大100,队列最大100*/
int num[20], i;
for (i = 0; i < 20; i++) {
num[i]=i;
threadPool_add(thp, process, (void*)&num[i]); /* 向线程池中添加任务 */
}
Sleep(1000); /* 等子线程完成任务 */
threadpool_destroy(thp);
return 0;
}
由于本人经验有限,如有错误,欢迎修正。