设为首页 加入收藏

TOP

C++实现线程池的经典模型
2014-11-24 08:08:00 来源: 作者: 【 】 浏览:0
Tags:实现 线程 池的 经典 模型

什么时候需要创建线程池呢?简单的说,如果一个应用需要频繁的创建和销毁线程,而任务执行的时间又非常短,这样线程创建和销毁的带来的开销就不容忽视,这时也是线程池该出场的机会了。如果线程创建和销毁时间相比任务执行时间可以忽略不计,则没有必要使用线程池了。


下面列出线程的一些重要的函数


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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇在Eclipse外使用JUnit测试 下一篇应用Libvirt连接KVM虚拟化平台

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·About - Redis (2025-12-26 08:20:56)
·Redis: A Comprehens (2025-12-26 08:20:53)
·Redis - The Real-ti (2025-12-26 08:20:50)
·Bash 脚本教程——Li (2025-12-26 07:53:35)
·实战篇!Linux shell (2025-12-26 07:53:32)