If the main thread completes before the child thread, then the child thread will be orphaned.
The main thread needs to wait for the child thread to complete.
We need to call t1.join() on the thread instance to make the main thread wait till t1 execution is complete.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<thread> | |
#include<iostream> | |
using namespace std; | |
void print() | |
{ | |
for (int i = 1; i <= 10; i++) | |
{ | |
cout << i << endl; | |
} | |
} | |
void main() | |
{ | |
thread t(print);//creating a thread instance | |
t.join();//main thread waits till child thread completes the task | |
cout << "main thread exiting" << endl; | |
} |
Also we need to check if a thread is joinable (thread with active code of execution), before calling join.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<thread> | |
#include<iostream> | |
using namespace std; | |
void print() | |
{ | |
for (int i = 1; i <= 10; i++) | |
{ | |
cout << i << endl; | |
} | |
} | |
void main() | |
{ | |
thread t(print);//creating a thread instance | |
if (t.joinable()) //check if the thread is joinable | |
t.join();//main thread waits till child thread completes the task | |
cout << "main thread exiting" << endl; | |
} |
No comments:
Post a Comment