I am facing a situation where it would be nice to launch an std::async
operation totally asynchronously.
future<void> MyClass::MyAsyncFunc() {
std::future<void> f = std::async(...);
return f;
} // The future goes out of scope, will block.
The problem is that the function will block at the end if I don't save the future. I would like this not to happen.
This would prevent the std::future
to call its destructor at the end of the function's scope:
shared_ptr<future<void>> MyClass::MyAsyncFunc() {
auto shared_ftr = std::make_shared<std::future<void>>();
*shared_ftr = std::async([shared_ftr]() {...});
return shared_ftr;
}
Could this possibly work? What happens when I don't save the result in a variable?
std::thread th{&foo}; th.detach();
? – HolzerMyAsyncFunc
will not block because it will only decrease the refcount, which should only go to 0 if the async execution is already stopped. – Lionelstd::future
even supported copy-construction. Last I checked it doesn't. – Depsidereturn
statement prefers moving if available. It does move here and does not block inside the function. – Laurelaureano