Thursday, 13 October 2016

Step by step multithreading : Detach()


First read below mentioned program -


#include <iostream>
#include <thread>
using namespace std;

void hello();

int main(int arvc, char **argv)
{
    thread t1(hello);
    t1.detach(); //introducing detach, now thread t1 is independent of main thread
    return 0;
}

void hello()
{
    cout<<"welcome to C++ multithreading";
}


Detach - 

When parent thread is not willing to wait for child thread to finish, we can use detach(), in that case child thread can run independently. Then child thread will become a daemon process.

When you detach any thread, it means we are just saying it can run and terminate independently, now there will not be any guarantee which thread (between child and parent thread) will get finish early. 

Which thread will finish early? Will depend upon the way we have implemented our business logic or how much work individual thread has to do.

Thanks for reading this, please write questions or some more useful information related to this topic on comment section. To learn more about threading, see the full learning index here, or join multithreading learning page on FB or on G++.

No comments:

Post a Comment