歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++實現線程池的經典模型

C++實現線程池的經典模型

日期:2017/3/1 10:00:57   编辑:Linux編程

什麼時候需要創建線程池呢?簡單的說,如果一個應用需要頻繁的創建和銷毀線程,而任務執行的時間又非常短,這樣線程創建和銷毀的帶來的開銷就不容忽視,這時也是線程池該出場的機會了。如果線程創建和銷毀時間相比任務執行時間可以忽略不計,則沒有必要使用線程池了。

下面列出線程的一些重要的函數

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();
};

Copyright © Linux教程網 All Rights Reserved