struct tp_thread_info_s{
pthread_t thread_id; //thread id num
TPBOOL is_busy; //thread status:true-busy;flase-idle
pthread_cond_t thread_cond;
pthread_mutex_t thread_lock;
tp_work *th_work;
tp_work_desc *th_job;
};
p_thread_pool_s 结构包含了有关线程池操作的接口和变量。在使用
creat_thread_pool 返 回一个线程池实例之后,首先要使用明确使用 init 接口
对它进行初始化。在这个初始化过程中,线程池会预创建指定的最小线程数目
的线程,它们都处于阻塞状 态,并不损耗 CPU,但是会占用一定的内存空间。
同时 init 也会创建一个线程池的管理线程,这个线程会在线程池的运行周期内
一直执行,它将定时的查看分 析线程池的状态,如果线程池中空闲的线程过多,
它会删除部分空闲的线程,当然它并不会使所有线程的数目小于指定的最小线
程数。
在已经创建并初始化了线程池之后,我们就可以指定 tp_work_desc_s 和
tp_work_s 结构,并使用线程池的 process_job 接口来执行它们。这些就是我
们使用这个线程池时所需要了解的所有东西。如果不再需要线程池,可以使用
close 接口销毁它。
三. 实现代码
Thread-pool.h(头文件):
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>
#include <signal.h>
#ifndef TPBOOL
typedef int TPBOOL;
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define BUSY_THRESHOLD 0.5 //(busy thread)/(all thread threshold)