Posted on 2012-07-17 16:33
點點滴滴 閱讀(856)
評論(0) 編輯 收藏 引用 所屬分類:
02 編程語言
Boost的thread庫中目前并沒有提供線程池,我在sorceforge上找了一個用boost編寫的線程池。該線程池和boost結合的比較好,并且提供了多種任務執行策略,使用也非常簡單。
下載地址:
http://threadpool.sourceforge.net/
使用threadpool:
這個線程池不需要編譯,只要在項目中包含其頭文件就可以了。
一個簡單的例子:
#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));
執行效率:
這個線程池的效率還沒有怎么測試過,目前還沒有應用到對性能要求比較高的地方,有時間測試一下。