Search code examples
c++c++11stdstdthreadstdasync

What happens to std::async call if parent/main thread dies


If I am right, the std::async uses a new thread and calls the method in it. I was wondering what happens if the main thread or the parent thread dies. Does the thread controlling the async method dies as well.


Solution

  • There is no concept of a "parent" thread in C++, each thread is independent of the one that it was created by. However, the main thread is special and if it returns from main() or calls exit() then the entire application is terminated even if other threads are still running. Once that happens, the program has undefined behaviour if the still-running threads access any global variables or automatic objects that were on the main thread's stack, or use any standard library objects or call any function not permitted in signal handlers.

    In short, do not let other threads run after main completes if you expect sensible results.