Boost的thread庫中目前并沒有提供線程池,我在sorceforge上找了一個用boost編寫的線程池。該線程池和boost結合的比較好,并且提供了多種任務執行政策,使用也非常簡單。
<a href="http://threadpool.sourceforge.net/">http://threadpool.sourceforge.net/</a>
這個線程池不需要編譯,隻要在項目中包含其頭檔案就可以了。
#include <iostream>
#include "threadpool.hpp"
using namespace std;
using namespace boost::threadpool;
// Some example tasks
void first_task()
{
cout << "first task is running\n" ;
}
void second_task()
cout << "second task is running\n" ;
void task_with_parameter(int value)
cout << "task_with_parameter(" << value << ")\n";
int main(int argc,char *argv[])
// Create fifo thread pool container with two threads.
pool tp(2);
// Add some tasks to the pool.
tp.schedule(&first_task);
tp.schedule(&second_task);
tp.schedule(boost::bind(task_with_parameter, 4));
// Wait until all tasks are finished.
tp.wait();
// Now all tasks are finished!
return(0);
一般異步調用中,傳回值的擷取有同步擷取和異步擷取兩種形式。
同步擷取傳回值:
int task_int_23()
cout<<"task_int_23()\n";
return 23;
future<int> res = schedule(tp, &task_int_23);
res.wait();
cout<<"get res value:"<<res.get()<<endl;
異步擷取傳回值:
不知道是設計者就不打算使用異步回調擷取傳回值還是我看的不夠仔細,異步擷取傳回值的方式還真沒有找着,隻好自己簡單的寫了一個回調的仿函數來實作異步傳回值的擷取。
//R為任務函數的傳回值類型
template<class R>
class callback_task
typedef boost::function<void (R)> callback;
typedef boost::function<R ()> function;
private:
callback c_;
function f_;
public:
//F: 任務執行函數 C:結果回調函數
template<class F,class C>
callback_task(F f,C c)
{
f_ = f;
c_ = c;
}
void operator()()
c_(f_());
};
通過這個對象可以很容易的實作異步結果的回調。
//task_int_23的結果回調函數
void callback(int k)
cout<<"get callback value:"<<k<<endl;
//通過回調的形式擷取任務的傳回值
tp.schedule(callback_task<int>(&task_int_23,&callback));
這個線程池的效率還沒有怎麼測試過,目前還沒有應用到對性能要求比較高的地方,有時間測試一下。