Mutex Locks C++ Multithreading Introduction

Mutex Locks C++ Multithreading Introduction


  • Mutex is the basic structure of synchronization.
  • It provides MUTUAL EXCLUSIVE access to shared data between multiple threads, by using a memory barrier.
In other words,
 The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously       accessed by multiple threads.

Member functions
  • (constructor)     Construct mutex. 
  • lock                   Lock mutex. 
  • try_lock             Lock mutex if not locked. 
  • unlock               Unlock mutex.
  • native_handle   Get native handle. 


  • Header | #include <mutex>
  • Declaration | std::mutex mutex_name;
  • To acquire the mutex | mutex_name.lock();
    The thread asks for ownership of the shared data protected by the mutex. It can successfully lock the mutex (and then no one else can access the same data) or block if the mutex is already locked by another thread.
  • To release the mutex mutex_name.unlock();
    When the resource is not needed anymore, the current owner must call, in order to let other threads access it. When the mutex is released, the access is permitted to a random thread among the waiting ones.

A sample code is written below which uses all the above mentioned

// mutex example
#include <iostream>       // std::cout
#include <thread>          // std::thread
#include <mutex>          // std::mutex

std::mutex mtx;             // declaring mutex for critical section

void print(int n) {
  // critical section (exclusive access to std::cout signaled by locking mtx):
  for (int i=0; i<n; ++i) 
      { std::cout << n;
  std::cout <<'\n';

int main ()
  std::thread th1 (print,5);   
  std::thread th2 (print,10);


  return 0;

55555                                    //5 times
10101010101010101010     //10 times

5 and 10 never mix together because of locks.