std::thread::join

join(): It basically temporarily halts the execution at the point where join() function is called till the thread associated with the calling object i.e. t_obj completes its task.  


std::thread::join [Advanced] -- [Click Here]


Let’s check the below examples.

Suggestion:- it would be great, if you copy following code and paste it on any online compiler (or vi/vim) and try to run it by your-self



Case-1: join() is not called

Case-2: join() is called

#include<iostream>
#include<thread> //Thread Header

using namespace std;


//“displayActivity” is the actual task
//to be performed by our thread


void displayActivity()
{
    for(int i=0;i<10;i++)
  cout<<"www.techsujhav.com : "<<i<<endl;
}

int main()
{
   cout<<"Going to start thread"<<endl;
   std::thread t_obj(displayActivity);

  //join() is intentionally commented
  //to check the behaviour of our code

  //t_obj.join();


    cout<<"Main exit"<<endl;
    return 0;
}
#include<iostream>
#include<thread> //Thread Header

using namespace std;

//“displayActivity” is the actual task
//to be performed by our thread


void displayActivity()
{
   for(int i=0;i<5;i++)
 cout<<"www.techsujhav.com : "<<i<<endl;
}


int main()
{
   cout<<"Going to start thread"<<endl;
   std::thread t_obj(displayActivity);
   
   cout<<"Before Join"<<endl;
   t_obj.join();
   cout<<"After Join"<<endl;
   cout<<"Main exit"<<endl;

   return 0;
}

Compile:
$g++ join.cpp  -o join -lpthread

Compile:
$g++ join.cpp  -o join -lpthread

Output:$ ./join

 

Going to start thread

Main exit

terminate called without an active exception

Aborted

 

Output:$ ./join

 

Going to start thread

Before Join

www.techsujhav.com : 0

www.techsujhav.com : 1

www.techsujhav.com : 2

www.techsujhav.com : 3

www.techsujhav.com : 4

After Join

Main exit

Observation (1):

We are not able to see any print from our task "displayActivity"   assigned to thread object. Although all other prints are visible from main ().

 

Explanation:

Once our thread object t_obj is created with “displayActivity” passed in constructor it notifies to OS (Operation System) to create a thread and constructor call finished and moved ahead for next instruction in main().

 

OS shall take some time (may be in nano-second) to create a thread, meanwhile main() has finished its activity and exited, therefore we don’t have any print of our task “displayActivity”

 

 

Observation(2):

terminate called without an active exception

Aborted

 

Explanation:

Will discuss in Advanced section of this post

Observation:

Our code worked as expected.

 

join() function halts execution of main and let the thread to finish assigned task.

 

More important to observe it that join() makes main to wait at the line it(join) is called.

PREV:: std::thread::get_id()

Your Comments /Suggestions & Questions are always welcome. 

We would like to help you with best of our knowledge.

So feel free to put Questions.


No comments:

Post a Comment