异步:boost async & boost future

如果需要用到异步(例如 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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值