用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;
}