赞
踩
C++0x提供了future和promise来简化任务线程间的返回值操作;
std::async是一个函数模板,会启动一个异步任务,最终返回一个std::future对象。
标准库中提供了3种future:
X v = f.get(); // if necessary wait for the value to get computed
如果它的返回值还没有到达,调用线程会进行阻塞等待。
等待超时,get()会抛出异常的(从标准库或等待的线程那个线程中抛出)
如果我们不需要等待返回值(非阻塞方式),可以简单询问一下future,看返回值是否已经到达:
if (f.wait_for(0))
{
// there is a value to get()
// do something
}
else
{
// do something else
}
// future<获取的结果类型> 变量名
// async(函数名, 参数)
std::future<int> fu = std::async(fun, 1);
std::cout << fu.get() << std::endl;
std::packaged_task是一个类模板,顾名思义是用来打包的,将一个可调用对象封装起来,然后可以将其的返回值传给future。
std::packaged_task<函数返回类型(参数类型)> 变量名(函数名)。
#include <iostream> #include <future> #include <thread> int fun(int x) { x++; x *= 10; std::cout << std::this_thread::get_id() << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); return x; } int main() { std::packaged_task<int(int)> pt(fun); // 将函数打包起来 std::future<int> fu = pt.get_future(); // 并将结果返回给future std::thread t(std::ref(pt), 1); std::cout << fu.get() << std::endl; std::cout << std::this_thread::get_id() << std::endl; t.join(); return 0; }
promise的主要目的是提供一个”put”(或”get”,随你)操作,以和future的get()对应。
try {
X res;
// compute a value for res
p.set_value(res);
}
catch (…) { // oops: couldn’t compute res
p.set_exception(std::current_exception());
}
void comp(vector& v) { // package the tasks: // (the task here is the standard // accumulate() for an array of doubles): packaged_task pt0{std::accumulate}; packaged_task pt1{std::accumulate}; auto f0 = pt0.get_future(); // get hold of the futures auto f1 = pt1.get_future(); pt0(&v[0],&v[v.size()/2],0); // start the threads pt1(&[v.size()/2],&v[size()],0); return f0.get()+f1.get(); // get the results }
#include <iostream> #include <future> #include <thread> int fun(int x, std::promise<int>& p) { x++; x *= 10; p.set_value(x); std::cout << std::this_thread::get_id() << std::endl; return x; } int main() { std::promise<int> p; std::future<int> fu = p.get_future(); // 并将结果返回给future std::thread t(fun, 1, std::ref(p)); std::cout << fu.get() << std::endl; // 当promise还没有值的时候在此等待 std::cout << std::this_thread::get_id() << std::endl; t.join(); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。