Updated April 1, 2023
Definition of C++ mutex
C++ mutax class is used to prevent our critical code to access from the various resources. Mutex is used to provide synchronization in C++ which means only one thread can access the object at the same time, By the use of Mutex keyword we can lock our object from being accessed by multiple threads at the same time.
Syntax:
We can lock and unlock the piece of code using Mutex in C++. We have to assign our code between these keywords. Below we can see the syntax for better understanding while using this in our program see below;
std::mutexmtx;
void function_name (arugeument_if _any) {
mtx.lock();
// your piece of code.
//logic goes here
mtx.unlock();
}
In the above example, we are using lock and unlock to surround our piece of code and prevent this from accessing from multiple threads at the same time. We can also see one practice example to understand it better while using in the program see below;
void print_block () {
mtx.lock();
std::cout<< 'hello';
mtx.unlock();
}
How does mutex Function work in C++?
As of now we know that we use Mutex to implement synchronization. This means by the use of this we can prevent our critical code from being modified by multiple threads at the same time. This is required when we have critical data not to be modified by the multiple threads because some values can be updated by the others thread which turns used somewhere else so in this senecios we cannot use this. We will also see one practice example where we need to lock the object from being modified by several threads at the same time. Mutex class provides us with two methods lock and unlock by which we can surround our logic inside this. It provides us several methods, but the basic thing it provides and is used for is to have synchronization in c++.
First, we will discuss the practice scenario where we need to lock the object while processing it. See below;
Let’s take one simple real-time example we need synchronization without it data would be inconsistent in the database. This can be easily understood by bank transactions. Suppose we have a single account for two members i.e. a joint account and let’s name them as A and B. On the whole, they have 2000 rupees in their account and they both want to withdraw this amount at the same time but in practice, this is not possible because only one person can get the amount. So we need to lock the resource for the same period of time when the first one ‘A’ will be done with their operations then only we will release the lock to avoid the inconsistency of data. So in this critical situation, we have mutex in place to handle those scenarios well. Otherwise, Bank and customer both have to suffer and the services we are providing them will be of no use. In such cases, we can implement and use mutex while programming.
- when to use mutex: Use mutex where we have shared resources and we do not want them to get modified by multiple or various threads at the same time. This is very important where we have business logic or some calculations which are dependent on the other data also, if we do not follow this approach then the data will be inconsistence or we can also receive some errors and exceptions as well.
Let’s see the member function which is available in Mutex see below;
- lock: We can use this member function to lock the object which we want to use. This object would be our shared resource which we do not want to be accessed by the mutex threads to prevent data consistency.
- unlock: We can use this member function to unlock out locked object so that after operations other thread can access it. If we do not unlock the object it will not allow other threads to access it, and the program may lead to a deadlock situation. So this is also required to continue our process normally for every thread.
- try_lock: This member function is used to lock the object but first it will check the object if it is blocked or not by the other thread. If not then it will lock the object otherwise not. In short, it will try to lock the object first.
- native_handle: This member function is used to get or return the native handle.
Let’s see one practice example to understand it better how it works internally and how we can implement it in our programming see below;
void myMethod () {
mtx.lock();
std::cout<< "values are ::";
for (int z=0; z< 10; ++z) {
std::cout<< z;
std::cout<< '\n';
}
std::cout<< "End of output !!";
mtx.unlock();
}
int main ()
{
std::cout<< "Demo for Mutex in C++";
// cretaingtherad here
std::thread thread1 (myMethod);
// therad
thread1.join();
return 0;
}
In the above example, we are creating our logic and trying to surround it by mutex in c++, here we have created one thread named ‘thread1’ and called our method from the first thread only. Immediately after this, we are calling join method from the thread. But as we noticed we have used the lock () and unlock () method to implement the mutex. Also, we have to use the import statement as well.
Example of C++ mutex
In this example, we are creating several threads and trying to access the same method with multiple threads. Let’s see the output after calling.
Example #1
Code:
#include <iostream>
// thread
#include <thread>
// mutex
#include <mutex>
std::mutexmtx;
void myMethod () {
mtx.lock();
std::cout<< "values are ::";
for (int z=0; z< 10; ++z) {
std::cout<< z;
std::cout<< '\n';
}
std::cout<< "End of output !!";
mtx.unlock();
}
int main ()
{
std::cout<< "Demo for Mutex in C++";
// cretaingtherad here
std::thread thread1 (myMethod);
std::thread thread2 (myMethod);
std::thread thread3 (myMethod);
// therad
thread1.join();
thread2.join();
thread3.join();
return 0;
}
Output:
Conclusion
By using mutex we can lock our object which holds the critical logic of our application. This also prevents data inconsistency as well which is very important in real-time applications. Mutex is used to implement synchronization like any other programming language.
Recommended Articles
This is a guide to C++ mutex. Here we also discuss the definition and how does mutex function work in c++? along with different examples and its code implementation. You may also have a look at the following articles to learn more –