C++ 11 – Multithreading

From C++ 11 onwards, multithreading is introduced. C++ developers can use these libraries without having to use external libraries such as pThreads. In this way, it is possible to write platform-independent code.

The most popular threading functions used in a C++ program are std::threadstd::mutexstd::lock_guardstd::atomic, and join.

Let us go through each of these functions using a practical C++ program. The program is available for download at https://github.com/codeversionmaster/cplusplus/blob/cplusplus17/multithread.cpp.

The header files to be included are as shown. The thread header file is for std::thread and join functionalities. The mutex header file is for std::mutex and std::lock_guard. The atomic header file is for std::atomic.

#include <iostream>
#include <thread>
#include <mutex>
#include <atomic>

mtx is a mutex lock created using the data type std::mutex.

count is an atomic variable. We will use mtx for mutex lock and then do any operations on the count variable.

There is no need for the atomic variable as mutex is already present. However, the usage is only to show the demo of the declaration of the atomic variable.

std::mutex mtx;
std::atomic<int> count(0);

The program starts at this point.

int main() {

We can create a mutex lock using the lock_guard function on variable mtx. Two threads t1 and t2 are created here.

One of them succeeds in getting the mutex lock and would do “count++” and increment the count variable.

    // Thread 1
    std::thread t1([&]() {
        std::lock_guard<std::mutex> lock(mtx);
        count++;
        std::cout << "Counter incremented by thread 1 to " << count << std::endl;
    });

    // Thread 2
    std::thread t2([&]() {
        std::lock_guard<std::mutex> lock(mtx);
        count++;
        std::cout << "Counter incremented by thread 2 to " << count << std::endl;
    });

The threads join the main program using the join function.

The final value of the count variable is displayed.

    t1.join();
    t2.join();

    std::cout << "Final count value: " << count << std::endl;

The program ends here.


    return 0;
}

You can compile and run the program as shown.

$ g++ -o multithread multithread.cpp 
$ ./multithread 
Counter incremented by thread 2 to 1
Counter incremented by thread 1 to 2
Final count value: 2