Each running program has at least one thread which is occupied by its entry point. There can be many threads for a single program and the memory is shared among all threads. The objects possessed by the main thread (and shared by other threads as a reference to it) would be destroyed as soon as they go out of scope. This might lead to corrupt memory access by the rest of the threads.
Hence, sometimes, it's very important to make sure that all the threads are joined using std::thread::join()
before the main thread terminates. Other times, you basically want a daemon thread running in background even after the termination of main thread and that can be achieved by calling std::thread::detach()
, but it may or may not be possible to join a detachable thread.
Resource Acquisition Is Initialization (RAII) is a famous programming idiom in C++ (a misnomer actually) also (better) known and understood as **Scope-Bound Resource Managemen