【c++】bind+function实现线程池

class Thread
{
public:
	//接收绑定器的类型:函数对象类型
	Thread(function<void()> func,int no):_func(func),_no(no) {}//没有参数,绑定器已经绑定过了
	thread start()
	{
		thread t(_func);//创建线程,线程函数给绑定器对象(在线程库底层调用运算符重载函数,参数已绑定)
		return t;
	}
private:
	function<void()> _func;
	int _no;
};

//线程池类
class ThreadPool
{
public:
	ThreadPool(){}
	~ThreadPool(){
		//指针没有析构函数,释放Thread对象占用的堆资源
		for (int i = 0; i < _pool.size(); ++i)
		{
			delete _pool[i];
		}
	}
	//开启线程池
	void startPool(int size) {
		//创建线程
		for (int i = 0; i < size; ++i) {
			//                    需要将它所有需要的函数绑定完:this,i值充当id
			_pool.push_back(
				//new Thread(bind(&ThreadPool::runInThread,this,i)));//thread需要线程函数  runInThread
				new Thread(bind(&ThreadPool::runInThread,this,_1),i));//thread需要线程函数  runInThread
				//整个绑定器返回函数对象,函数对象调用相当于任何参数都不用传。函数对象本身不依赖于其他对象,是底层的runInThread调用时需要依赖当前线程池对象
		}
		//调用线程对象的每个start方法
		for (int i = 0; i < size; ++i) {
			//                    需要将它所有需要的函数绑定完:this,i值充当id
			_handler.push_back(_pool[i]->start());
		}
		for (thread& t : _handler)
		{
			t.join();//等待所有子线程完成,主线程才结束
		}
	}
private:
	vector<Thread*> _pool;//线程类new出来
	vector<thread> _handler;//线程类句柄
	
	//把runInThread方法充当线程函数
	void runInThread(int id) {
		cout << "call runInThread ! id:" << id << endl;
	}
};

int main()
{
	ThreadPool pool;
	pool.startPool(10);//开启十个线程
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值