See the Tutorial List

Multithreading in C++

Multithreading means two or more threads running concurrently where each thread is handling a different task. When you login to you Facebook profile, on your news feed, you can see live videos, you can comment or hit a like button, everything simultaneously. This is the best example of multithreading. Multithreading environment allows you to run many activities simultaneously; where different threads are responsible for different activities.

There are various uses of Multithreading, some of them are:

  • Better resource utilization.
  • Simpler program design.
  • More responsive programs.

What is a Thread?

Thread is generally referred as a light weight process. Each thread executes different parts of a program. Each thread shares memory, file descriptors and other system resources. In Linux, all thread functions are declared in <pthread.h> header file. But it is not available in standard C++ library.


Creating Threads in Linux(C++)

  1. pthread_create(): It creates a new thread. Below is the syntax:
    pthread_create(threadID, attr, start_routine, arg)

    In the code above:

    threadID: Is a unique identifier for each thread. ThreadID of threads are compared using pthread_equal() function.

    attr: Attribute object that may be used to set various thread attributes. It controls interaction of thread with rest of the program.

    start_routine: The C++ routine that the thread will execute once it is created.

    arg: Single argument must be passed by reference as a pointer of type void. If no argument is to be passed, null can be used.

  2. pthread_exit(): It is used to terminate any thread.

Below is a simple program on creating threads in C++:

#include <iostream>
#include <pthread.h>
using namespace std;

char* str = "Child thread";

void* func(void *str)
{
    cout << "Child thread Created: " << (char*)str;
}
// main function
int main()
{
    s = ctime(&Time);
    // Step 1: Declaring thread
    pthread_t t;    
    // Step 2: Calling create thread function
    pthread_create(&t, NULL, &func, (void*)str); 
    /*
        Syntax for pthread_create is:
        pthread_create(threadID,attr,start_routine,arg)
        Here,
        threadID = t, arg = (void*)str, atrr = Null, start_routine = func
    */
    cout << "Main thread created" << endl;
    pthread_join(t, NULL);
    //Exiting after completion
    exit(EXIT_SUCCESS); 
    return 0;
}

Main thread created Child thread created: Child thread


Joining and Detaching Threads

There are two methods which we can use to join or detach threads:


join() function

Joining of a thread is done by using the join() function of the thread class. It makes main thread and child thread inter dependent. Main thread terminates only after child thread terminates i.e. main thread waits for child thread to complete execution.

Syntax:

threadname.join();

It returns once all functions are completed. A thread is not joinable when it is assigned to another thread or when join() or detach() is called.

Syntax:

/* 
    It checks whether a thread is joinable. 
    It returns bool value.
*/
threadname.joinable(); 

detach() function

The detach() function detaches a thread from the parent thread. It allows both main thread and child thread to execute independently.

Syntax:

threadname.detach();

Program Example for using join() method

Let's have a simple example to demonstrate the use of join() function to join two threads:

#include <iostream>
#include <unistd.h>   // To include sleep function
#include<ctime>   // To get system time
#include <pthread.h>
using namespace std;

string s;
time_t Time = time(0);

void* func(void*)
{
    s = ctime(&Time);
    sleep(1);   //C alls sleep function
    cout << "Child thread Created " << s << endl;
}

// main function
int main()
{
    s = ctime(&Time);
    //Step 1: Declaring thread
    pthread_t t1[5];
    for(int i=0; i<5; i++)
    {
        cout << "Thread T[" << i << "] is Created " << s << endl;
        // Step 2: calling create thread function
        pthread_create(&t1[i], NULL, &func, NULL); 
        // Joining threads, main thread waits for child thread to complete
        pthread_join(t1[i], NULL); 
}
//Exiting after completion
exit(EXIT_SUCCESS); 
return 0;
}

Thread T[0] is Created Wed Nov 1 02:30:57 2017 Child thread Created Wed 1 02:30:57 2017] Thread T[1] is Created Wed Nov 1 02:30:57 2017 Child thread Created Wed 1 02:30:57 2017 Thread T[2] is Created Wed Nov 1 02:30:57 2017 Child thread Created Wed 1 02:30:57 2017 Thread T[3] is Created Wed Nov 1 02:30:57 2017 Child thread Created Wed 1 02:30:57 2017 Thread T[4] is Created Wed Nov 1 02:30:57 2017 Child thread Created Wed 1 02:30:57 2017


Program Example for using detach() method

Let's have a simple example to demonstrate the use of join() function to detach two threads:

#include <iostream>
#include <unistd.h>   // To include sleep function
#include<ctime>   // To get system time
#include <pthread.h>
using namespace std;

string s;
time_t Time = time(0);

void* func(void*)
{
    s = ctime(&Time);
    sleep(1);   // Calls sleep function
    cout << "Child thread Created " << s << endl;
}

// main function
int main()
{
    s = ctime(&Time);
    // Step 1: Declaring thread
    pthread_t t1[5]; 
    for(int i=0; i<5; i++)
    {
        cout << "Thread T[" << i << "] is Created " << s << endl;
        // Step 2: Calling create thread function
        pthread_create(&t1[i], NULL, &func, NULL); 
        // Step 3: main thread doesn't waits for child thread to complete
        pthread_detach(t1[i]); 
}
// Exiting after completion
exit(EXIT_SUCCESS); 
return 0;
}

Thread T[0] is Created Wed Nov 1 02:38:14 2017 Thread T[1] is Created Wed Nov 1 02:38:14 2017 Thread T[2] is Created Wed Nov 1 02:38:14 2017 Thread T[3] is Created Wed Nov 1 02:38:14 2017 Thread T[4] is Created Wed Nov 1 02:38:14 2017

Hoope you have understood the concept of thread creation in C++.