1. 首先到官網下載
2. 包含頭文件
#include
"../boost/threadpool.hpp"
3. 聲明threadpool對象,
boost::threadpool::fifo_pool m_poolCmdProcess;
上面聲明了一個FIFO線程池, 即先進先出
4. 聲明一個Runnable適配類 來包裝你的類及成員函數
class Runnable
{
typedef boost::function<void (/*CCommunicationMap*, */ICommandContextEx*)> function;
private:
function _f;
CCommunicationMap* _target;
ICommandContextEx* _data;
public:
template<class F>
Runnable(CCommunicationMap* target, F f, ICommandContextEx* data)
{
_f = f;
_target = target;
_data = data;
}
~Runnable(){}
void run()
{
//_target->TestCommand(_data);
_f(/*_target, */_data);
}
};
上面 function 聲明了一個函數模板, 此模板應該和你要關聯的類成員函數類型一致。
5. 調用threadpool的schedule方法 啟動線程
fun = boost::bind(&CCommunicationMap::TestCommand, &m_communication, _1);
Runnable* run = new Runnable(&m_communication, fun, pContext);
boost::threadpool::schedule(m_poolCmdProcess, boost::shared_ptr<Runnable>(run));
注意:
threadpool庫中的pool_adaptors.hpp頭文件有錯誤, 需要我們改動源碼(注釋的為原來代碼,下面的為改動后的代碼), 具體為:
template<typename Pool, typename Runnable>
bool schedule(Pool& pool, shared_ptr<Runnable> const & obj)
{
//return pool->schedule(bind(&Runnable::run, obj));
return pool.schedule(bind(&Runnable::run, obj));
}