C++ 11 feature: C++ Multithreading Tutorial: Mutex in C++ threading

In this chapter we shall learn about below topics;

Mutex stands for Mutual Exclusion.

What is mutual exclusion?

To answer this question, we need to understand what is Race Condition?

A race condition is a situation where two or more threads or process trying to modify the data at the same time.

Race condition occurs when two or more process/threads trying to modify the data. Race condition will not occur while reading the data.

What is critical section?

Where there is a race condition on a section of code, that section of code is called as critical section or region. We have to protect it.

Now, what is mutual exclusion?

Mutual exclusion is a concept that is used to prevent race condition.

Now lets see in real time how race condition occurs.

In below example 3 threads are trying to increment the value “count”.

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

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;

int count = 0;


void incrementCount()
{
   count++;//critial section
   cout<<count<endl;
}

int main(void)
{
    std::thread t1(incrementCount);
    std::thread t2(incrementCount);
    std::thread t3(incrementCount);

    t1.join();
    t2.join();
    t3.join();
    return 0;
}

output:

1
3
2

From the output you can see that, the value is not incrementing according to sequence 1, 2, 3. But it is incrementing like 1, 3, 2. This is not the expected result.

Because 3 threads are continuously trying to change the value.

We can solve these kind of race condition with the help of Mutex.

C++ 11 Mutex provides 2 functions, lock() and unlock() to prevent race condition.

We lock the critical section before modifying and unlock the section after modifying. Thus avoiding race condition.

Example:

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

// for more tutorial in C++ visit www.prodevelopertutorial.com

using namespace std;

int count = 0;

std::mutex mu;

void incrementCount()
{
    mu.lock();
    
   count++;//critial section
   cout<<count<<endl;
   
   mu.unlock();
}

int main(void)
{
    std::thread t1(incrementCount);
    std::thread t2(incrementCount);
    std::thread t3(incrementCount);

    t1.join();
    t2.join();
    t3.join();
    
    
    return 0;
}

Output:

1
2
3

As you can see from above, we got the expected output.

So you might be getting the question if mutex and thread synchronization are same?

No, they are not. But Mutex is a locking mechanism and using mutex multiple threads synchronize to access critical section.

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *