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); /*增加任务*/