c++ - boost::future and continuations - value set, but future still blocks -
i trying make following continuation work - 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 "done:"
, future fires, it'll "hang" on f.get()
.. 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: following code change make example work - 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: following, adding launch policy launch::deferred
, work:
foo.start().then(boost::launch::deferred, [](boost::future<int> f) { std::cout << "done:" << std::endl; std::cout << f.get() << std::endl; });
and also:
boost::future<int> start() { boost::future<int> f = p.get_future(); f.set_deferred(); return f; }
the problem is, composed future not kept around. in fact, temporary , gets destructed 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 prints
done: 23
see live on coliru
if move f2.get()
before foo.finish()
dead lock again.
Comments
Post a Comment