When attaching a continuation to boost::future
, the continuation is executed in a new thread:
std::cout << "main: " << boost::this_thread::get_id() << std::endl;
boost::promise<void> p;
boost::future<void> f = p.get_future();
p.set_value();
boost::future<void> f2 = f.then([] (boost::future<void>) {
std::cout << "future: " << boost::this_thread::get_id() << std::endl;
});
This snippet outputs:
main: 0x7fff7a8d7310
future: 0x101781000
Why is .then()
allowed to do that, and, more importantly, is there a way to customise this behaviour? Do future
s returned from promise
/packaged_task
/async
behave differently?
It is already mentioned in @ikh answer. But to make it more clear, here is the direct answer to the OP question.
It is customizable whether boost::future
continuation should be executed in a new thread or in the calling thread.
boost::launch
policy parameter specifies how the continuation should run. See here: Enumeration launch
enum class launch
{
none = unspecified,
async = unspecified,
deferred = unspecified,
executor = unspecified,
inherit = unspecified,
any = async | deferred
};
A future created by
async(launch::deferred, ...)
or::then(launch::deferred, ...)
has associated a launch policylaunch::deferred
.
So, try running this:
boost::future<void> f2 = f.then(
boost::launch::deferred,
[] (boost::future<void>&&) {
std::cout << "future: " << boost::this_thread::get_id() << std::endl;
}
);
That should run the continuation in the same thread.
Tested with boost 1.61 + Visual Studio 2015 on Windows platform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With