thread::join [Advanced] - Why do we need to call join() on thread object?

Question:-1, Why do we need to call join() on thread object, although created thread has already finished its task?

Question:-2, Why does program lead to abort if join() is not called?

Question:-3, Is it necessary to call join() or detach() on a thread Object?

Explanation:

Thread remain in ACTIVE state even though it has finished its assigned task. [Just scroll through the joinable () section]

Now if we do not call join() then state remains active i.e. joinable() == true and hence once thread-object goes out of scope it will call it’s destructor and inside the destructor there is check that if  joinable() == true then call std::teriminate. Our program will stopped abruptly there itself.

NOTE:- It is important to observe that every event/operation (join/detach/joinable etc.) happening with thread-object, not with thread that Operating System is running.

 Failure Case

 Success case

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

using namespace std;

//actual task to be performed
//by our thread


void displayActivity()
{
cout<<"www.techsujhav.com : "<<endl;
}

int main()
{
     cout<<"Going to start thread"<<endl;

    {
//New scope started.

       std::thread t_obj(displayActivity);

      //Below for loop just to consume time
      //to show that "displayActivity" finished

        for(int i=0; i<900000000;i++);

        cout<<"Going out of scope"<<endl;

     }//<--program aborted here only

     cout<<"Main Exit"<<endl;

     return 0;

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

using namespace std;

//actual task to be performed
//by our thread

void displayActivity()
{
cout<<"www.techsujhav.com : "<<endl;
}

int main()
{
    cout<<"Going to start thread"<<endl;
   
    {//New scope started.

       std::thread t_obj(displayActivity);
       cout<<"Before Join, (ACTIVE) joinable="           <<t_obj.joinable()<<endl;

        t_obj.join();

       cout<<"After Join, (ACTIVE) joinable=" 
       <<t_obj.joinable()<<endl;

       cout<<"Going out of scope"<<endl;
     }//<--End of scope

     cout<<"Main Exit"<<endl;

      return 0;
}

Output: $ ./join

Going to start thread

www.techsujhav.com :

Going out of scope

terminate called without an active exception

Aborted

$ ./join

Going to start thread

Before Join, ACTIVE (joinable())=1

www.techsujhav.com :

After Join, ACTIVE (joinable())=0

Going out of scope

Main Exit

Important to note that “Main Exit” is not displayed in output. 

Now it clearly visible that destructor has performed it’s activity without calling std::terminate.



Question-3: What will happen if we call join again on same thread?

PREV:: std::thread::join [Advanced]

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