ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

C++ 11 feature: C++ Multithreading Chapter 3: Attaching and detaching threads in C++

prodevelopertutorial February 26, 2020

In the first 2 chapters we saw an introduction and different ways to create a thread in C++. In this chapter we shall see ways to attach and detach a thread.

Joining a thread using “join()”.

Why there is a need to call join()?

Once we create a thread, the main program needs to wait till the execution of the thread is completed.
To make main thread wait till the execution of the threads to be completed, we call “join()”.

Simple example:

Below program we have created a thread, and joined it to main thread.

#include <iostream>
#include <thread>

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;

void myFun(int num)
{
    while(num > 0)
    {

        cout<<num<<endl;
        num --;

    }
}

int main(void)
{

    std::thread t1(myFun, 5);
    t1.join();

    return 0;
}

Example program to simulate that the program waits at “.join()”

#include <iostream>
#include <thread>
#include <unistd.h> // for usleep

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;

void myFun(int num)
{
    while(num > 0)
    {
        cout<<num<<endl;
        num --;
    }

    usleep(500000);
}

int main(void)
{

    std::thread t1(myFun, 5);
    cout<<"Before Join"<<endl;

    t1.join();

    cout<<"After join"<<endl;

    return 0;
}
Output:

Before Join
5
4
3
2
1
After join

If you run the program, the statement “cout<<“After join”<<endl;” will wait for 5 sec, i.e till the execution of the thread is complete then it will be printed.

Calling “.join()” two or more times on the same thread object will result in program termination

#include <iostream>
#include <thread>

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;

void myFun(int num)
{
    while(num > 0)
    {
        cout<<num<<endl;
        num --;
    }
}

int main(void)
{
    std::thread t1(myFun, 5);
    
    //calling ".join()" twice
    t1.join();
    t1.join();
    
    return 0;
}
Output:
terminate called after throwing an instance of 'std::system_error'
what(): Invalid argument

So to prevent a thread to be joined 2 or more times, use “joinable()” function to know if the thread can be joined or not.

joinable() will return true if we need to join the thread, else false if the thread is already joined.

Example:

#include <iostream>
#include <thread>
#include <unistd.h> // for usleep

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;

void myFun(int num)
{
        cout<<num<<endl;
}

int main(void)
{
    std::thread t1(myFun, 5);


    if (t1.joinable())    
    {
        cout<<"First time joining"<<endl;
        t1.join();
    }
    
     if (t1.joinable())    
    {
        cout<<"Second time joining, it will not be printed"<<endl;
        t1.join();
    }
    
    return 0;
}

Output:

First time joining
5

Detach()

We use “detach()” function to detach a thread from parent thread.

Simple example:

In the program below, we have not joined the thread, but we have detached the thread.

#include <iostream>
#include <thread>
#include <unistd.h> // for usleep

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;

void myFun(int num)
{
    cout<<"Start function"<<endl;
    usleep(1000000);
    cout<<"End function"<<endl;    
}

int main(void)
{
    std::thread t1(myFun, 5);

    cout<<"In main"<<endl;
    
    t1.detach();
    
    cout<<"After main"<<endl;


    
    return 0;
}

 

Output:

In main
After main
Start function

In the output above, we can see that, the main thread did not wait till the execution of the thread is complete. It quit before it.

Note: Similar to double attach problem, same program termination occurs for double detach() of the thread. Hence, before detaching a thread, check if it is join-able. If the thread is joinable then only we detach the thread.

#include <iostream>
#include <thread>
#include <unistd.h> // for usleep

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;

void myFun(int num)
{
    cout<<"In myFun"<<endl;
}

int main(void)
{
    std::thread t1(myFun, 5);

    cout<<"In main"<<endl;
    
    t1.join();
    
    if(t1.joinable())
        t1.detach();
        
    if(t1.joinable())
        t1.detach();
    
    cout<<"After main"<<endl;


    
    return 0;
}

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT