std::thread::detach

detach() function detaches the thread-object with execution of thread. All resource shall be release by thread once it exists i.e. completed its tasks.

As we know that join() put a halt on process execution at the point where join is called but there are certain situation where programmer wants execution to move ahead in code and let the created thread to do its task independently, (not waiting for thread complete its task)there we can call detach().

Example where detach can be better

  • if a thread is always listening on a socket.
  • if you want certain activity on every interval say every 5 mins.
  • Probably an activity assigned to task where there is infinite loop then that can be detached.
std::thread::detach()[Advanced] -[Click Here]

Let check following code, Moreover output how it is overlapped.

#include<iostream>

#include<thread>
#include<chrono>

using namespace std;

//"
displayActivity" is the actual task
//performed by detached thread
void displayActivity()
{
    for(int i=0;i<5;i++)
        cout<<"www.techsujhav.com"<<endl;
}

int main()
{
    std::thread t1(displayActivity);

    t1.detach();

    for(int i=0;i<5;i++)
    {
        cout<<"Performing Activity in main()"<<endl;
    
        //intentionally putting sleep of 1-neno second.
        //for better display of out example.

        std::this_thread::sleep_for(1ns);
    }
    return 0;
}

Compile: $g++ detach.cpp –o detach -lpthread

$ ./detach


Performing Activity in main()
Performing Activity in main()
www.techsujhav.com
www.techsujhav.com
www.techsujhav.com
www.techsujhav.com
www.techsujhav.com
Performing Activity in main()
Performing Activity in main()
Performing Activity in main()

PREV:: std::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