bind函数模板加function函数对象实现C++线程池

        用bind函数和function函数简单实现一个C++的线程池。 

#include<iostream>
#include<vector>
#include<thread>
#include<functional>
using namespace std;
class Thread
{
public:
	//这里的func没有参数,而且返回值为空,这主要是因为bind函数已经将所有参数绑定完毕了,返回了一个void()的函数对象
	Thread(function<void()>func):myfunc(func){}
	~Thread() {}
	thread start()
	{
		 thread t(myfunc);
		return t;
	}
private:
	function<void()>myfunc;
};
class ThreadPool
{
public:
	ThreadPool(int size=10):size(size) {}
	~ThreadPool() 
	{
		for (int i = 0; i < size; i++)
		{
			delete threadpool[i];
			threadpool[i] = nullptr;
		}
	}
	void startpool()
	{
		for (int i = 0; i < size; i++)
		{
			//由于bind函数只接受普通的C函数,但是run函数是一个类成员函数,run函数如果要充当一个普通的C函数
			//那么就需要将所有参数绑定完,包括用来传递当前对象的Test*参数
			threadpool.push_back(new Thread(bind(&ThreadPool::run, this, i)));
		}
		for (int i = 0; i < size; i++)
		{
			handler.push_back(threadpool[i]->start());
		}
		for (int i = 0; i < size; i++)
		{
			handler[i].join();//主线程等待所有子线程执行完
		}
	}
private:
	int size;
	vector<Thread*>threadpool;
	vector<thread>handler;
	void run(int id)
	{
		cout << this_thread::get_id() << " id:" << id << endl;
	}
};
int main()
{
	ThreadPool pool(20);
	pool.startpool();
	return 0;
}

      

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咩咩大主教

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值