I have the following code:
#include
#include
#include
#include
using namespace std;
int sleep
I know this is an old question, but it still comes up as the top result for "detach std::future" when searching. I came up with a simple template based approach to handle this:
template
std::future startDetachedFuture(FUNCTION_TYPE func) {
std::promise pro;
std::future fut = pro.get_future();
std::thread([&func](std::promise p){p.set_value(func());},
std::move(pro)).detach();
return fut;
}
and you use it like so:
int main(int argc, char ** argv) {
auto returner = []{fprintf(stderr, "I LIVE!\n"); sleep(10); return 123;};
std::future myFuture = startDetachedFuture(returner);
sleep(1);
}
output:
$ ./a.out
I LIVE!
$
If myFuture goes out of scope and is destructed, the thread will carry on doing whatever it was doing without causing problems because it owns the std::promise and its shared state. Good for occasions where you only sometimes would prefer to ignore the result of a computation and move on (my use case).
To the OP's question: if you get to the end of main it will exit without waiting for the future to finish.