线程池(Thread Pool)是一种多线程处理形式,处理过程中将任务提交给一个线程集合,而不是直接由操作系统管理线程的创建和销毁。线程池的主要目的是通过重用线程来减少线程创建和销毁的开销,以及通过管理线程的数量来防止系统过载。
线程池通常包括以下几个部分:
- 线程池管理:负责创建、销毁和线程池。
- 工作线程:线程池中真正执行任务的线程。
- 管理线程:动态管理线程池的存活线程个数(任务多则多开,少则减少存活线程数)
- 任务队列:用于存放待处理的任务。
线程池的主要优点包括:
- 降低资源消耗:通过重用已存在的线程,可以降低线程创建和销毁的开销。
- 提高响应速度:当任务到达时,任务可以不需要等待线程创建就能立即执行。
- 提高线程的可管理性:线程是稀缺资源,如果无限制地创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <string>
#include<signal.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#define DEFAULT_TIME 10
#define DEFAULT_STEP 15
using namespace std;
int dp[20]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
/*线程工作任务*/
typedef struct
{
void *(*function)(void *);
void *arg;
} thread_task;
/*线程池管理*/
struct pthread_pool
{
pthread_mutex_t lock; //锁整个线程池
pthread_mutex_t busylock; //锁忙线程数量
pthread_cond_t queue_not_full; //任务队列未满的信号
pthread_cond_t queue_not_empty; //任务对列不为空的信号
pthread_t *th;
pthread_t adjustth; //维护线程,任务过多或者过少时调节线程池的线程总数
int min_thr_num;
int max_thr_num;
int live_thr_num;
int busy_thr_num;
int wait_exit_num;
thread_task *queue_task; //任务队列
int queue_front;
int queue_rear;
int queue_size;
int queue_maxsize;
bool status = false;
};
void *process(void *);
void pthread_free(pthread_pool *pool) //线程池资源的释放
{
if(pool->queue_task)
{
free(pool->queue_task);
}
if(pool->th)
{
free(pool->th);
pthread_mutex_lock(&(pool->lock));
pthread_mutex_destroy(&(pool->lock));
pthread_mutex_lock(&(pool->busylock));
pthread_mutex_destr