什么时候需要创建线程池呢?简单的说,如果一个应用需要频繁的创建和销毁线程,而任务执行的时间又非常短,这样线程创建和销毁的带来的开销就不容忽视,这时也是线程池该出场的机会了。如果线程创建和销毁时间相比任务执行时间可以忽略不计,则没有必要使用线程池了。
下面列出线程的一些重要的函数
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
void pthread_exit(void *retval);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_init(pthread_cond_t *restrict cond,
const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_init(pthread_cond_t *restrict cond,
const pthread_condattr_t *restrict attr);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);
下面是用C++实现线程池源码:
在该源码中,有两个文件,一个头文件pmutil.h, 一个源文件pmulti.cpp文件
下面是 pmuti.h 文件
#include <pthread.h>
typedef struct worker_node{ /*任务结点*/
void *(*process)(void *arg);
void *arg;
worker_node *next;
}worker_node;
typedef struct worker_queue{/*任务队列*/
private:
worker_node * head ,*tail ;
int cur_size ;
pthread_cond_t ready ;/**保持同步*/
pthread_mutex_t mutex ; /**保持互斥信号*/
bool destroy ;
public:
worker_queue();
~worker_queue();
int clean(); /*清空队列*/
int in_queue(const worker_node *node); /*任务入队*/
worker_node * out_queue(); /*任务出队*/
} worker_queue ;
class pmulti{
private:
pthread_t * threads ;
unsigned int thread_num;
mutable worker_queue * w_queue;
bool is_init;
bool is_destroy;
enum {QUEUE_MAX_SIZE=100};
public:
pmulti();
~pmulti();
int init(unsigned int num=10);
static void * thread_fun(void *arg); /*线程执行主函数*/
int add_worker(const worker_node * node); /*增加任务*/
int destroy();
};