c:c_threads:troubleshooting:program_crashes:forgetting_to_join_a_thread
Differences
This shows you the differences between two versions of the page.
c:c_threads:troubleshooting:program_crashes:forgetting_to_join_a_thread [2021/06/07 08:58] – created peter | c:c_threads:troubleshooting:program_crashes:forgetting_to_join_a_thread [2021/06/07 08:58] (current) – peter | ||
---|---|---|---|
Line 1: | Line 1: | ||
====== C - C++ Threads - Troubleshooting - Program Crashes - Forgetting to join a thread ====== | ====== C - C++ Threads - Troubleshooting - Program Crashes - Forgetting to join a thread ====== | ||
+ | |||
+ | Forgetting to join a thread or detach it (make it unjoinable) before the main program terminates, will cause in a program crash. | ||
+ | |||
+ | For example, the t1 thread is not joined to the main thread. | ||
+ | |||
+ | <code cpp> | ||
+ | #include < | ||
+ | #include < | ||
+ | using namespace std; | ||
+ | |||
+ | |||
+ | void HelloWorld() | ||
+ | { | ||
+ | cout << "Hello World" << endl; | ||
+ | } | ||
+ | |||
+ | |||
+ | int main() | ||
+ | { | ||
+ | thread t1(HelloWorld); | ||
+ | // | ||
+ | return 0; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <WRAP info> | ||
+ | **NOTE: | ||
+ | |||
+ | * This is because, at the end of the main function, thread t1 goes out of scope and the thread destructor is called. | ||
+ | * Inside the destructor, a check is performed to see if thread t1 is joinable. | ||
+ | * A joinable thread is a thread that has not been detached. | ||
+ | * If the thread is joinable, std:: | ||
+ | </ | ||
+ | |||
+ | |||
+ | ---- | ||
+ | |||
+ | ===== Resolution ===== | ||
+ | |||
+ | There are two ways to fix this depending on your needs. | ||
+ | |||
+ | ==== 1. Join the thread t1 to the main thread ==== | ||
+ | |||
+ | <code cpp> | ||
+ | int main() | ||
+ | { | ||
+ | thread t1(HelloWorld); | ||
+ | t1.join(); | ||
+ | return 0; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ---- | ||
+ | |||
+ | ==== 2. Detach the thread t1 from the main thread and let it continue as a daemon thread ==== | ||
+ | |||
+ | <code cpp> | ||
+ | int main() | ||
+ | { | ||
+ | thread t1(HelloWorld); | ||
+ | t1.detach(); | ||
+ | return 0; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ---- | ||
c/c_threads/troubleshooting/program_crashes/forgetting_to_join_a_thread.1623056296.txt.gz · Last modified: 2021/06/07 08:58 by peter