std::mutex in C++

In this post, we are going to learn about std::mutex in C++. Synchronization is needed when processes need to execute concurrently i.e. for the sharing of resources with no obstruction. We will discuss how to do this with the help of std::mutex.

What is std::mutex?

In C++, std::mutex is a simple synchronization structure that is used to protect data that is accessed by multiple threads. It means Mutual Exclusive access to shared data between multiple threads. You can make a mutex object and use lock() and unlock() functions to make a portion of your code only available to one thread at a time.

#include<iostream>
#include <mutex>

std::mutex m;

m.lock();

/*************************************************************/
/*     This portion of code will become the critical section */
/*     Only one thread can access this portion at a time     */
/*************************************************************/

m.unlock();

As explained above, only one thread will be able to access the critical section once the lock() method is called until the unlock() method is called. So if another thread wishes to enter the critical section it would have to wait till the first thread has reached the unlock() call.

There are 3 functions you can use with std :: mutex:

  1. lock() – this method locks the mutex and only one thread will be able to access the critical section at a time.
  2. unlock() – this is for unlocking the mutex now another thread can access the critical section.
  3. try_lock() – this is for a thread to try to lock the mutex, it will return false if the mutex isn’t available.

You should always keep in mind to use the unlock() method otherwise the mutex resource i.e. the critical section will be unavailable for the entire program.

C++ program for demonstrating the use of std::mutex

#include <iostream>
#include<mutex>
#include<thread>
using namespace std;
mutex m;           // creating a mutex for critical section

void printer (int n, char c) {
    // critical section (exclusive access to std::cout signaled by locking m):
   //using lock() method so that only one thread can access the
  //portion at a time.This marks the begining of the critical section
m.lock();
  for (int i=n; i>=0; i--) {
    cout << c;
   }
  std::cout << endl;
  m.unlock(); //using unlock() method which marks the end of the critical section
}

int main ()
{
  thread thread_a (printer,35,'#');
  thread thread_b (printer,35,'%');

  thread_a.join();
  thread_b.join();

  return 0;
}

Output for the above Code

std::mutex in C++

Note – On Linux machines, you will have to use -pthread argument when compiling on the terminal using g++.

Recommended Posts:
std::extent() template in C++

Leave a Reply

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