Loading...
C++ Multithreading

C++ Multithreading

In this tutorial, we will learn about Multithreading in C++ with the help of examples.

Multithreading

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:
1. Better resource utilization.
2. Simpler program design.
3. 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.

std::thread is the thread class that represents a single thread in C++. To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable.

A callable can be either of the three:
1. A function pointer
2. A function object
3. A lambda expression
After defining callable, pass it to the constructor.

#include <thread>
std:: thread thread_object(callable )

thread using function pointer

The following code snippet demonstrates how this is done

void foo(param)
{
    // do something
}
// The Parameters to the function are put after the comma
std:: thread thread_obj(foo, params);

thread using lambda expression

The following code snippet demonstrates how this is done

// Define a lamda expression
class fn_object-class{
    // Overload () operator
    void operator(params)
    {
        // do something
    }
}
// Create thread object
std:: thread thread_object(fn_object-class_object(), params);

Waiting for threads to finish

Once a thread has started we may need to wait for the thread to finish before we can take some action. For instance, if we allocate the task of initializing the GUI of an application to a thread, we need to wait for the thread to finish to ensure that the GUI has loaded properly.

To wait for a thread use the std::thread::join() function. This function makes the current thread wait until the thread identified by *this has finished executing.
For instance, to block the main thread until thread t1 has finished we would do

int main()
{
    // start thread t1
    std:: thread t1(callable);

    // wait for thread 't1' to finish
    t1.join();

    // t1 has finished do other stuff

    ...
}

Example 1: C++ Program to demonstrate Multithreading

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

// A Dummy Function
void foo(int Z){

    for (int i = 0; i < Z; i++) {
        cout << "Thread using function Pointer as callable \n";
    }
}
// A Callable Object
Class thread_obj{
    public: 
    void operator(int x){

        for (int i = 0; i < x; i++) {
            cout << "Thread using function object as callable \n";
        }
    }
};
int main(){

    cout << "Threads 1 and 2 and 3 operating independently \n";
    // This thread is launched by using function pointer as callable
    thread th1 (foo, 3);

    // This thread is launched by using function object as callable
    thread th2 (thread_obj(), 3);
    
    // Define a lamba Expression
    auto f = [](int x){

        for (int i = 0; i < x; i++) {
            cout << "Thread using lambda expression as callable \n";
        };
    };

    // This thread is launched by using lambda expression as callable
    thread th3 (f, 3);
    
    // wait for the threads to finish
    // wait for the thread t1 to finish
    th1.join();

    // wait for the thread t2 to finish
    th2.join();

    // wait for the thread t3 to finish
    th3.join();
    
    return 0;
}

Output

Threads 1 and 2 and 3 operating independently
Thread using function pointer as callable
Thread using lambda expression as callable
Thread using function pointer as callable
Thread using lambda expression as callable
Thread using function object as  callable
Thread using lambda expression as callable
Thread using function pointer as callable
Thread using function object as  callable
Thread using function object as  callable

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.

Example 2: C++ Program to demonstrate Multithreading

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: \n" << (char*) str;
}

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_create (t, NULL);
    // Exiting after completion
    exit(EXIT_SUCCESS);

    return 0;
}

Output

Main thread created
Child thread created: Child thread

Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of Multithreading in C++.

Keep Learning : )

In the next tutorial, you'll learn about C++ Standard Library.

- Related Topics