Wednesday 12 October 2016

Step by step multithreading : Join()

C++ 11 has introduced multithreading in standard library. Let us see some basic concepts and learn threading.

First look at the below mentioned program -

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

void hello();

int main(int arvc, char **argv)
{
    thread t1(hello);
    t1.join(); // join means, main thread will wait for t1 to complete.
    return 0;
}

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

/*
compilation command -
    g++ -std=c++11 program.cpp

output -
    welcome to C++ multithreading
*/

Note: you have to compile this program through C++11 compiler.

Here, we have two new things to notice.
  1. #include <thread> // which is added in C++ 11 standard library. To achieve multithreading in C++.
  2. We have passed a function (here function is hello()) to the thread object. 
  3. And last but not least Join() , see the description below.

Join - 

This is a function of thread class, which will tell the main thread, wait until your child thread gets completed, after child thread is completed then only main thread will start, and then execute further instructions.


To understand more just see another easy example (focus on the output), in below mentioned example, first main thread waits for child thread (t01) to complete, then control goes to next statement, then it again waits for child thread (this time t02) to complete, and then finishes the program. 


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

void hello_by_thread01();
void hello_by_thread02();

int main(int arvc, char **argv)
{
    thread t01(hello_by_thread01);
    t01.join(); // join means, main thread will wait for t01 to complete.
    cout<< endl << "now in main thread from thread 01";
    
    thread t02(hello_by_thread02);
    t02.join(); // join means, main thread will wait for t02 to complete.
    cout<< endl << "now in main thread from thread 02";
    
    return 0;
}

void hello_by_thread01()
{
    cout<<"welcome to C++ multithreading, through thread 01";
}
void hello_by_thread02()
{
    cout<<endl<<"welcome to C++ multithreading, through thread 02";
}
/*
compilation command -
    g++ -std=c++11 FileName.cpp

output -
$ ./a.exe
welcome to C++ multithreading, through thread 01
now in main thread from thread 01
welcome to C++ multithreading, through thread 02
now in main thread from thread 02
*/

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