一:介绍
前段时间看到一篇用c语言写的一个线程池,觉得思路蛮清晰的
http://blog.youkuaiyun.com/zouxinfox/archive/2008/12/19/3560891.aspx
而自己对线程池内部实现一直朦朦胧胧的,也一直想锻炼下,故按照作者思路写了个c++版本。不对的地方希望大家指出来我再改
正!!!
二: 源文件
一共三个文件,ThreadPool.h ThreadPool.cpp main.cpp
ThreadPool.h
ThreadPool.cpp
main.cpp
编译指令:g++ -o ThreadPool ThreadPool.cpp main.cpp -lpthread
运行结果:
xinshuow@xinshuow-desktop:~/TestDir/OSPorject/ThreadPool$ ./ThreadPool
CThreadPoolManager::CThreadPoolManager()
Start thread 0xb7853b70
Thread 0xb7853b70 is waiting .
Start thread 0xb7052b70
Thread 0xb7052b70 is waiting .
Start thread 0xb6851b70
Thread 0xb6851b70 is waiting .
Thread id is 0xb7853b70 working on task 0
Thread id is 0xb7052b70 working on task 1
Thread id is 0xb6851b70 working on task 2
Thread id is 0xb7853b70 working on task 3
Thread id is 0xb7052b70 working on task 4
Thread id is 0xb6851b70 working on task 5
Thread id is 0xb7853b70 working on task 6
Thread id is 0xb7052b70 working on task 7
Thread id is 0xb6851b70 working on task 8
Thread id is 0xb7853b70 working on task 9
Thread 0xb7052b70 is waiting .
Thread 0xb6851b70 is waiting .
Thread 0xb7052b70 will exit
Thread 0xb6851b70 will exit
Thread 0xb7853b70 will exit
CThreadPoolManager::~CThreadPoolManager()
xinshuow@xinshuow-desktop:~/TestDir/OSPorject/ThreadPool$
三: 说明
我觉得C版本有个问题:在主线程里用sleep(5)来等待所有线程退出,但当业务逻辑(即用户注册的线程回调函数)需要花费很长时间处
理事务时, 线程退出可能是不安全的。
C++版本的思路与C版本思路相差无几,只是在主线程退出时做了个循环判断,这样可以避免C版本中使用的sleep机械式地等待线程退出!