bind和function实现muduo中的线程池
大约 1 分钟
bind和function实现muduo中的线程池
#include <iostream>
#include <typeinfo>
#include <string>
#include <memory>
#include <vector>
#include <functional>
#include <thread>
using namespace std;
using namespace placeholders;
//线程类
class Thread
{
public:
Thread(function<void(int)> func, int no)//使用function接收bind
:_func(func), _no(no) {}
thread start()
{
thread t(_func, _no);// _func(_no)
return t;
}
private:
function<void(int)> _func;//存储线程处理函数
int _no;
};
//线程池类
class ThreadPool
{
public:
ThreadPool() {}
~ThreadPool()
{
//因为vector存储的是指针,所以需要手动释放资源
//释放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(&ThreadPool::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;
//把runInThread这个成员方法充当线程函数 thread pthread_create
void runInThread(int id)
{
cout << "call runInThread! id:" << id << endl;
}
};
int main()
{
ThreadPool pool;
pool.startPool(10);
return 0;
}
- 不管是C++中的thread还是Linux中的pthread_create,需要的线程函数都是C函数,是不能够使用成员方法的,不可能将一个成员方法的函数指针扔给C的函数指针。
- 编译之后需要一个对象,将当前对象this绑定上去
