Upon creating a thread it is started immediately:
#include <thread>
void worker() {
// Business logic.
}
int main () {
std::thread t(worker);
return 0;
}
This preceding code would start the thread to then immediately terminate the application, because we are not waiting for the new thread to finish executing.
To do this properly, we need to wait for the thread to finish, or rejoin as follows:
#include <thread>
void worker() {
// Business logic.
}
int main () {
std::thread t(worker);
t.join();
return 0;
}
This last code would execute, wait for the new thread to finish, and then return.