C++ 实现线程池的精典模型
什么时候需要创建线程池呢?简单的说,如果一个应用需要频繁的创建和销毁线程,而任务执行的时间又非常短,这样线程创建和销毁的带来的开销就不容忽视,这时也是线程池该出场的机会了。如果线程创建和销毁时间相比任务执行时间可以忽略不计,则没有必要使用线程池了。
下面列出线程的一些重要的函数
void * test(void* i){ printf("test:%d\n",( int)i); sleep(1); return NULL;}int main(int argc,char ** args){ printf("this is main!\n"); class pmulti pm; pm.init(15); worker_node no ; for(int i=0;i<5;i++){ no.process = &test ; no.arg = (void*)(i*2); pm.add_worker(&no); } sleep(5); pm.destroy(); return 0;}运行结果:
g++ multi.cpp multi.h -lpthread -o multi
[test@localhost multi_thread]$ ./multi
this is main!
thread num:24531909488
test:0
thread num:3046583152
test:2
thread num:3036093296
test:4
thread num:3025603440
test:6
thread num:3015113584
test:8
thread num:3004623728
thread num:3067562864
thread num:2994133872
thread num:2983644016
thread num:2973154160
thread num:2962664304
thread num:2952174448
thread num:2941684592
thread num:2931194736
thread num:3078052720
thread_fun:24531909488 run
thread_fun:3046583152 run
thread_fun:3036093296 run
thread_fun:3025603440 run
thread_fun:3015113584 run
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
joined :0 end;
参考博客:http://hi.baidu.com/boahegcrmdghots/item/f3ca1a3c2d47fcc52e8ec2e1