boost::future and continuations - value set, but f

2019-02-27 10:08发布

I am trying to make the following continuation work - but f.get() blocks. Whats wrong?

#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();
}

It'll print the "done:", so the future fires, but it'll then just "hang" on f.get() .. I am lost.

To build:

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

UPDATE: The following code change will make the example work - but why? Since f2 isn't used anyway. Puzzled again.

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

UPDATE 2: The following, adding a launch policy launch::deferred, will also work:

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

and this also:

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

1条回答
混吃等死
2楼-- · 2019-02-27 10:20

The problem is, your composed future is not kept around. In fact, it is a temporary and it gets destructed as soon as the statement (with .then()) ends.

Fix it:

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();
}

Now it prints

done:
23

See it Live On Coliru

If you move the f2.get() before the foo.finish() it will dead lock again.

查看更多
登录 后发表回答