Linux 线程池 C 实现

Linux 线程池 C 实现

ID:39465423

大小:48.00 KB

页数:7页

时间:2019-07-04

Linux 线程池 C 实现_第1页
Linux 线程池 C 实现_第2页
Linux 线程池 C 实现_第3页
Linux 线程池 C 实现_第4页
Linux 线程池 C 实现_第5页
资源描述:

《Linux 线程池 C 实现》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库

1、一个Linux下C线程池的实现2009-01-0521:18     什么时候需要创建线程池呢?简单的说,如果一个应用需要频繁的创建和销毁线程,而任务执行的时间又非常短,这样线程创建和销毁的带来的开销就不容忽视,这时也是线程池该出场的机会了。如果线程创建和销毁时间相比任务执行时间可以忽略不计,则没有必要使用线程池了。  下面是Linux系统下用C语言创建的一个线程池。线程池会维护一个任务链表(每个CThread_worker结构就是一个任务)。  pool_init()函数预先创建好max_thread_num个线程,每个线程执

2、thread_routine()函数。该函数中1.while(pool->cur_queue_size==0)2.{3.      pthread_cond_wait(&(pool->queue_ready),&(pool->queue_lock));4.}表示如果任务链表中没有任务,则该线程出于阻塞等待状态。否则从队列中取出任务并执行。    pool_add_worker()函数向线程池的任务链表中加入一个任务,加入后通过调用pthread_cond_signal(&(pool->queue_ready))唤醒一个出于阻塞状

3、态的线程(如果有的话)。    pool_destroy()函数用于销毁线程池,线程池任务链表中的任务不会再被执行,但是正在运行的线程会一直把任务运行完后再退出。下面贴出完整代码1.#include2.#include3.#include4.#include5.#include6.#include7.8./*9.*线程池里所有运行和等待的任务都是一个CThread_worker10.*由于所有任务都在链表

4、里,所以是一个链表结构11.*/12.typedefstructworker13.{14.    /*回调函数,任务运行时会调用此函数,注意也可声明成其它形式*/1.    void*(*process)(void*arg);2.    void*arg;/*回调函数的参数*/3.    structworker*next;4.5.}CThread_worker;6.7.8./*线程池结构*/9.typedefstruct10.{11.    pthread_mutex_tqueue_lock;12.    pthread_co

5、nd_tqueue_ready;13.14.    /*链表结构,线程池中所有等待任务*/15.    CThread_worker*queue_head;16.17.    /*是否销毁线程池*/18.    intshutdown;19.    pthread_t*threadid;20.    /*线程池中允许的活动线程数目*/21.    intmax_thread_num;22.    /*当前等待队列的任务数目*/23.    intcur_queue_size;24.25.}CThread_pool;26.27.2

6、8.intpool_add_worker(void*(*process)(void*arg),void*arg);29.void*thread_routine(void*arg);30.31.32.staticCThread_pool*pool=NULL;33.void34.pool_init(intmax_thread_num)35.{36.    pool=(CThread_pool*)malloc(sizeof(CThread_pool));37.38.    pthread_mutex_init(&(pool->queu

7、e_lock),NULL);39.    pthread_cond_init(&(pool->queue_ready),NULL);40.41.    pool->queue_head=NULL;42.43.    pool->max_thread_num=max_thread_num;1.    pool->cur_queue_size=0;2.3.    pool->shutdown=0;4.5.    pool->threadid=6.        (pthread_t*)malloc(max_thread_num*si

8、zeof(pthread_t));7.    inti=0;8.    for(i=0;ithreadid[i]),NULL,thread_

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。