c++线程池的一种实现


    多线程编程中经常需要使用线程池,在此本人实现了一种线程池,共大家参考。

 

      此版本使用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-----------

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值