User Tools

Site Tools


c:c_threads:important_considerations:ensure_that_threads_are_joined_or_detached_before_terminating_an_application

C - C++ Threads - Important Considerations - Ensure that threads are joined or detached before terminating an application

Use join() to wait for background threads before terminating an application.

#include <iostream>
#include <thread>
 
void ShowMessage()
{
  std::cout << "Hello World" << std::endl;
}
 
int main()
{
  std::thread t1(ShowMessage);
  //t1.join();  // Not joining to the main thread will cause a crash!
  return 0;
}

NOTE: Notice the join in the main() is commented out.

This will cause a program crash.


Solution

Here are some ways to fix this:

1. Join the t1 thread to the main thread

int main()
{
  std::thread t1(ShowMessage);
  t1.join();   // Join t1 to the main thread.
  return 0;
}

2. Detach the t1 thread from the main thread and let it continue as a daemon thread

int main()
{
  std::thread t1(ShowMessage);
  t1.detach();  // Detach t1 from main thread.
  return 0;
}

c/c_threads/important_considerations/ensure_that_threads_are_joined_or_detached_before_terminating_an_application.txt · Last modified: 2021/03/05 09:33 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki