最近看boost的文档,才发现原来1.41和以后的版本的thread库里面已经有相关的东西做这件事了
这个就是 boost::unique_future 和 boost::shared_future.
用起来很方便,下面是示例
#include <boost/thread.hpp>
#include <string>
using namespace std;
using namespace boost;
int calculate_the_answer_to_life_the_universe_and_everything(int par, string aaa)
{
if(aaa == "hello")
return par-1;
else
return par+1;
}
int main(void)
{
int a = 33;
string b = "hello";
boost::packaged_task<int> pt(boost::bind(calculate_the_answer_to_life_the_universe_and_everything, a, b));
boost::unique_future<int> fi=pt.get_future();
boost::thread task(boost::move(pt)); // launch task on a thread
fi.wait(); // wait for it to finish
assert(fi.is_ready());
assert(fi.has_value());
assert(!fi.has_exception());
assert(fi.get_state()==boost::future_state::ready);
// assert(fi.get()==42);
int aaa = fi.get();
return 0;
}
--
caosuwei <caosuwei@gmail.com>
没有评论:
发表评论