读书人

Linux平台上线程池的原理及实现

发布时间: 2012-08-09 15:59:21 作者: rapoo

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

下面是Linux系统下用C语言创建的一个线程池。线程池会维护一个任务链表(每个CThread_worker结构就是一个任务)。

pool_init()函数预先创建好max_thread_num个线程,每个线程执thread_routine ()函数。该函数中

      #include <stdio.h>
      1. void *
      2. myprocess (void *arg){
      3. printf ("threadid is 0x%x, working on task %d\n", pthread_self (),*(int *) arg); sleep (1);/*休息一秒,延长任务的执行时间*/
      4. return NULL;}

      5. int
      6. main (int argc, char **argv){
      7. pool_init (3);/*线程池中最多三个活动线程*/
      8. /*连续向池中投入10个任务*/ int *workingnum = (int *) malloc (sizeof (int) * 10);
      9. int i; for (i = 0; i < 10; i++)
      10. { workingnum[i] = i;
      11. pool_add_worker (myprocess, &workingnum[i]); }
      12. /*等待所有任务完成*/ sleep (5);
      13. /*销毁线程池*/ pool_destroy ();

      14. free (workingnum);
      15. return 0;}
      将上述所有代码放入threadpool.c文件中,
      在Linux输入编译命令
      $ gcc -o threadpool threadpool.c -lpthread

      以下是运行结果
      starting thread 0xb7df6b90
      thread 0xb7df6b90 is waiting
      starting thread 0xb75f5b90
      thread 0xb75f5b90 is waiting
      starting thread 0xb6df4b90
      thread 0xb6df4b90 is waiting
      thread 0xb7df6b90 is starting to work
      threadid is 0xb7df6b90, working on task 0
      thread 0xb75f5b90 is starting to work
      threadid is 0xb75f5b90, working on task 1
      thread 0xb6df4b90 is starting to work
      threadid is 0xb6df4b90, working on task 2
      thread 0xb7df6b90 is starting to work
      threadid is 0xb7df6b90, working on task 3
      thread 0xb75f5b90 is starting to work
      threadid is 0xb75f5b90, working on task 4
      thread 0xb6df4b90 is starting to work
      threadid is 0xb6df4b90, working on task 5
      thread 0xb7df6b90 is starting to work
      threadid is 0xb7df6b90, working on task 6
      thread 0xb75f5b90 is starting to work
      threadid is 0xb75f5b90, working on task 7
      thread 0xb6df4b90 is starting to work
      threadid is 0xb6df4b90, working on task 8
      thread 0xb7df6b90 is starting to work
      threadid is 0xb7df6b90, working on task 9
      thread 0xb75f5b90 is waiting
      thread 0xb6df4b90 is waiting
      thread 0xb7df6b90 is waiting
      thread 0xb75f5b90 will exit
      thread 0xb6df4b90 will exit
      thread 0xb7df6b90 will exit

读书人网 >UNIXLINUX

热点推荐