Thursday, 25 June 2020

Multithreading: 2.Join and Joinable

Most of the times the main thread may execute in a shorter period of time than the child threads.
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.

#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;
}
view raw jointhread.cpp hosted with ❤ by GitHub

Also we need to check if a thread is joinable (thread with active code of execution), before calling join.
#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;
}
view raw Joinable.cpp hosted with ❤ by GitHub

No comments:

Post a Comment