多线程编程中经常需要使用线程池,在此本人实现了一种线程池,共大家参考。
此版本使用c++在redhat linux 64位系统实现,可快速改为win32版本。
概要介绍:
cthread_pool维护线程池,客户程序通过cthread_pool取空闲线程,取到cprocess_thread指针后调用begin_run函数,传递this指针和pvoid(客户程序需要的参数),pvoid会在线程回调时原封不动传到线程中,当任务处理完成后,调用cthread_pool的free_thread释放线程回线程池。主要涉及互斥、信号量的操作。
类介绍:
1 cthread 线程基类,封装了线程的创建(pthread_create)和停止(pthread_join),定义线程函数(虚函数_thread_fun):
-----------------------------------thread.h-----------------------------------------
class cthread { public: cthread(void); virtual ~cthread(void); protected: void run(); void stop(); private: pthread_t m_thread; static void * _thread(void * p); virtual void * _thread_fun(void * p) = 0; };
--------------------------thread.cpp---------------------------
cthread::cthread(void) { } cthread::~cthread(void) { } void cthread::run() { pthread_create(&m_thread,NULL,_thread,this); } void cthread::stop() { pthread_join(m_thread,NULL); } void * cthread::_thread(void * p) { cthread * pthread = (cthread*)p; return pthread->_thread_fun(p); }
2 ccallback_base类,定义回调函数
------------------------------callback_base.h-----------