c++ - boost::future 和 Continuations - 值已设置,但 future 仍然受阻

标签 c++ boost future continuations

我正在尝试使以下延续工作 - 但 f.get() block 。怎么了?

#include <iostream>

#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
#include <boost/thread/future.hpp>

struct Foo {

   boost::future<int> start() {
      return p.get_future();
   }

   void finish() {
      p.set_value(23);
   }

   boost::promise<int> p;
};

int main () {

   Foo foo;

   foo.start().then([](boost::future<int> f) {
      std::cout << "done:" << std::endl;
      std::cout << f.get() << std::endl;
   });

   foo.finish();
}

它会打印 "done:",所以 future 会被触发,但它会在 f.get() 上“挂起”.. 我我迷路了。

构建:

clang++ -o test8 -std=c++11 -stdlib=libc++ -lboost_thread -lboost_system \
  -I/home/oberstet/boost_1_55_0 -L/home/oberstet/boost_1_55_0/stage/lib \
  test8.cpp

更新:以下代码更改将使示例正常运行 - 但为什么呢?因为 f2 无论如何都没有被使用。又疑惑了。

   boost::future<void> f2 = foo.start().then([](boost::future<int> f) {
      std::cout << "done:" << std::endl;
      std::cout << f.get() << std::endl;
   });

更新 2:以下添加启动策略 launch::deferred 也将起作用:

   foo.start().then(boost::launch::deferred, [](boost::future<int> f) {
      std::cout << "done:" << std::endl;
      std::cout << f.get() << std::endl;
   });

还有这个:

   boost::future<int> start() {
      boost::future<int> f = p.get_future();
      f.set_deferred();
      return f;
   }

最佳答案

问题是,你的 future 并没有被保留。事实上,它是一个临时变量,一旦语句(使用 .then())结束,它就会被破坏。

修复它:

int main () {
    Foo foo;

    auto f1 = foo.start();
    auto f2 = f1.then([](boost::future<int> f) {
        std::cout << "done:" << std::endl;
        std::cout << f.get() << std::endl;
    });

    foo.finish();
    f2.get();
}

现在打印

done:
23

查看 Live On Coliru

如果将 f2.get() 移到 foo.finish() 之前,它将再次死锁。

关于c++ - boost::future 和 Continuations - 值已设置,但 future 仍然受阻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22617420/

相关文章:

c++ - 清除 boost::array

firebase - 按下按钮时如何显示与 FutureBuilder 的对话框?

scala - 在 Akka/Scala 中使用带有 future 的 mapTo

java - 在 Java 中使用 CompletableFuture 并行执行 for 循环并记录执行

c++ - MinGW + GVim 编译 C/C++ 失败(没有那个文件或目录)

gnuSTL_shared 的 Android NDK 构建问题

c++ - 从 boost::property_tree::ptree::iterator 获取 ptree

c++ - Boost rng vs OpenCV rng vs c++11 std::random?

c++ - 如何在 C++ 中使用或模拟 lookbehind 断言?

c++ - 为什么 std::nth_element 返回 N < 33 元素的输入 vector 的排序 vector ?