Linux C thread pool to achieve the basic logic structure

 

// 描述线程池相关信息
struct threadpool_t {
	pthread_mutex_t lock;           // 用于锁住本结构体
	pthread_mutex_t thread_counter; // 记录忙碌状态线程个数的锁
	pthread_cond_t queue_not_full;  // 当任务队列满时, 添加任务的线程阻塞,等待条件变量
	pthread_cond_t queue_not_empty; // 任务队列里不为空时,通知等待任务的线程

	pthread_t *threads;             // 存放线程池中每个线程的tip,数组
	pthread_t adjust_tid;           // 存放管理线程的tid
	threadpool_task_t* task_queue;  // 任务队列

	int min_thr_num;                // 线程池最小线程数
	int max_thr_num;                // 线程池最大线程数
	int live_thr_num;               // 当前存活线程个数
	int busy_thr_num;               // 忙状态线程个数
	int wait_exit_thr_num;          // 要销毁的线程个数

	int queue_front;                // 任务队列对头下标
	int queue_rear;                 // 任务队列队尾下标
	int queue_size;                 // 任务队列中的任务数
	int queue_max_size;             // 任务队列中可容纳的任务上限

	int shutdown;                   // 标志位,线程池使用的状态 true/false

};

Thread pool is a structure, the structure is encapsulated four threads for synchronization lock. A member for locking the entire structure, is used to lock a number of busy threads

A condition variable, when the task queue is full, add a thread blocks

A condition variable, when the queue is not empty, waiting for the task notification thread

Wherein the stored array structure of tid thread, a thread management thread tid

There is a task queue.

A (thread number of threads in the initial state) stored minimum number of threads

The maximum number of storage (maximum number of threads) thread

A variable represents the number of threads now surviving, a variable represents the number of threads busy state.

A variable represents the number of threads to be destroyed.

For the task queue, the queue HOL package, the tail, the length of the queue and the maximum capacity

Each queue element is a function pointer, as the callback

// 任务结构体
typedef struct {
	void* (*fundction)(void*);      // 函数指针, 回调函数
	void* arg;                      // 上面函数的参数
}threadpool_task_t;

Then a variable indicates that the queue is closed.

 

 

 

Guess you like

Origin blog.csdn.net/wwxy1995/article/details/94592777