If I run it with launch::async then I know it will run anyway (I think thats what I read), but do I have to call get / wait in order to perform some sort of clean up.
I dont need the result, I just want a nice fire and forget.
You should call get or wait if you want to ensure that the task finishes. If you dont call get or wait the system will terminate the task when the parent thread terminates.
This can have undefined behaviour if youre dealing with resource management in the child thread (ie pointers or something on the heap). Even if this isn't explicit in the parent thread, it could creep up somewhere else in your program.
In addition, it would be confusing for other programmers who might be unsure whether you intentionally excluded the call to get/wait or forgot it accidentally
Put attention, that destructor of returned future object will perform blocking wait until your task action will finish (and the corresponded shared state will become ready).
See last paragraph on the page: https://en.cppreference.com/w/cpp/thread/future/~future
If you want to make sure no one will ever think that you mistakenly forgot to use get
, I'll recommend you to use std::thread
instead, and then call .detach
on it. This way no one will be able to call .join
on it, because it won't be joinable
anymore.
For more details, see: Can I use std::async without waiting for the future limitation?
"I just want a nice fire and forget." -- then std::async
is not the right tool. Just launch a thread and detach it:
std::thread thr(my_function);
thr.detach();
std::async
is basically about computing a result, possibly in a separate thread, and eventually being able to access that result. It returns an object of type std::future<whatever>
that gives you that result. If you don't care about the result, you don't need the bookkeeping overhead. Further, it's possible that std::async
won't do anything at all until you try to get the result. So if you don't try to get the result, you don't get "fire and forget" in any meaningful sense.