0

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.

pm100
  • 48,078
  • 23
  • 82
  • 145

4 Answers4

3

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

mattyx17
  • 806
  • 6
  • 11
2

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

Daniel Zin
  • 479
  • 2
  • 7
2

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?

Coral Kashri
  • 3,436
  • 2
  • 10
  • 22
0

"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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • He has expressed that the "launch::async" policy was applied, so I think you are wrong. The action definitely will be fired! – Leon Jun 25 '20 at 10:09
  • @Leon -- you're right about `launch::async`. Still not the right tool. – Pete Becker Jun 25 '20 at 11:55
  • I agree with "std::async is not the right tool". In fact I have adopted your solution, i.e. to launch a raw thread directly. Thank you very much!!! – Leon Jun 26 '20 at 15:57