如果需要用到异步(例如 io 等待, 大量计算)执行代码,boost async 和 future 提供了方便的操作:
补充,查看这里:http://blog.csdn.net/gw569453350game/article/details/50435879
#include <boost/thread/future.hpp>
using namespace boost;
int main()
{
future<int> f1 = async([]() { return 123; }); // or any heavy computation
future<string> f2 = f1.then([](future<int> f) { return f.get().to_string(); // here .get() won't block;
}
上面的代码需要保存 f1
变量,否则async
返回一个临时的 future
变量,然后就被销毁了,该future
的销毁会导致主程序等待异步被执行的函数的返回(即阻塞)。因此,即使不需要使用async 所执行的函数的返回值,也需要用一个f1来保存其返回的future变量,否则会阻塞异步执行(即 async 只有在计算完成后才会返回),例如:
void f()
{
std::future<void> fut = std::async(std::launch::async,
[] { /* compute, compute, compute */ });
} // block here until thread spawned by std::async completes
The function blocks until the asychronously running thread completes.
因为:
The thread completion [for the function run asynchronously] synchronizes with [i.e., occurs before] [1] the return from the first function that successfully detects the ready status of the shared state or [2] with the return from the last function that releases the shared state, whichever happens first.
但是如果使用的不是 async,则不会出现阻塞的情况:
void f3()
{
std::packaged_task<void()> pt(doSomeWork);
auto fut = pt.get_future();
std::thread(std::move(pt)).detach();
... // no get, no wait
}
Now what happens?
Your function returns, even if the function to be run asynchronously is still running.
注意: boost::future 只能 get 一次,第二次get返回的是空!
参考链接
1. http://www.boost.org/doc/libs/1_59_0/doc/html/thread/synchronization.html#thread.synchronization.futures
2. http://scottmeyers.blogspot.hk/2013/03/stdfutures-from-stdasync-arent-special.html
3. http://scottmeyers.blogspot.hk/2013/03/thread-handle-destruction-and.html
4. http://www.boost.org/doc/libs/1_59_0/doc/html/thread/build.html#thread.build.configuration.future