I wrote this sample code to test boost::future
continuations to use in my application.
#include <iostream>
#include <functional>
#include <unistd.h>
#include <exception>
#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
#include <boost/thread/future.hpp>
void magicNumber(std::shared_ptr<boost::promise<long>> p)
{
sleep(5);
p->set_value(0xcafebabe);
}
boost::future<long> foo()
{
std::shared_ptr<boost::promise<long>> p =
std::make_shared<boost::promise<long>>();
boost::future<long> f = p->get_future();
boost::thread t([p](){magicNumber(p);});
t.detach();
return f;
}
void bar()
{
auto f = foo();
f.then([](boost::future<long> f) { std::cout << f.get() << std::endl; });
std::cout << "Should have blocked?" << std::endl;
}
int main()
{
bar();
sleep (6);
return 0;
}
When compiled, linked and run with boost version 1.64.0_1, I am getting following output:
Should have blocked?
3405691582
But according to boost::future::then
's documentation here.
The execution should be blocked at f.then()
in function bar()
because the temporary variable of type boost::future<void>
should block at destruction, and the output should be
3405691582
Should have blocked?
In my application though, the call to f.then()
is blocking the execution till continuation is not invoked.
What is happening here?