bind绑定器返回的结果还是一个函数对象
bind是函数模板,可以自动推演模板类型参数
class Thread
{
public:
Thread(function<void(int)> func,int no):_func(func),_no(no) {}
thread start()
{
thread t(_func,_no);//_func(_no)
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)
{
_pool.push_back(new Thread(bind(&Thread::runInThread,this,_1),i));
}
for(int i=0;i<size;++i)
{
_handler.push_back(_pool[i]->start());
}
for(thread& t : _handler)
{
t.join();
}
}
private:
vector<Thread*> _pool;
vector<thread> _handler;
void runInThread(int id)
{
cout << "call runInThread!id:" << id << endl;
}
}:
int main()
{
ThreadPool pool;
pool.startPool(10);
return 0;
}