The thread class provides the join() function if you want to wait for it to finish. Here is a modified version of the previous example that waits for the background thread:
#include <thread>#include <iostream>void print_numbers_in_background(){ // code omitted for brevity}int main(){ std::thread background{print_numbers_in_background}; // the while loop omitted for brevity background.join();}
As we already discussed previously, the thread function is run as a separate entity independently from other threads- even the one that started it. It won't wait for the thread it has just started, and that's why you should explicitly tell the caller function to wait for it to finish. It is necessary to signal that the calling thread ...