Waiting for threads

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

Get Expert C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.