线程池设计
数据结构设计
任务设计
typedef struct tp_work_desc_s TpWorkDesc; typedef void (*process_job)(TpWorkDesc*job); struct tp_work_desc_s { void *ret; //call in, that is arguments void *arg; //call out, that is return value }; |
其中,TpWorkDesc是任务参数描述,arg是传递给任务的参数,ret则是任务处理完成后的返回值;
process_job函数是任务处理函数原型,每个任务处理函数都应该这样定义,然后将它作为参数传给线程池处理,线程池将会选择一个空闲线程通过调用该函数来进行任务处理;
线程设计
typedef struct tp_thread_info_s TpThreadInfo; 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; process_job proc_fun; TpWorkDesc* th_job; TpThreadPool* tp_pool; }; |
TpThreadInfo是对一个线程的描述。
thread_id是该线程的ID;
is_busy用于标识该线程是否正处理忙碌状态;
thread_cond用于任务处理时的唤醒和等待;
thread_lock,用于任务加锁(此处保留);
proc_fun是当前任务的回调函数地址;
th_job是任务的参数信息;
tp_pool是所在线程池的指针;
线程池设计
typedef struct tp_thread_pool_s TpThreadPool; struct tp_thread_pool_s { unsigned min_th_num; //min thread number in the pool unsigned cur_th_num; //current thread number in the pool unsigned max_th_num; //max thread number in the pool pthread_mutex_t tp_lock; pthread_t manage_thread_id; //manage thread id num TpThreadInfo* thread_info; Queue idle_q; TPBOOL stop_flag; }; |