C++ Thread synchronization via mutex

Introduction

Threads sometimes need to access the same object.

In our example, both threads are accessing the global std::cout object in order to output the data.

This can be a problem.

This means we need to synchronize the access to a shared std::cout object somehow.

While one thread is writing to it, we need to ensure that the thread does not write to it.

We do so by locking and unlocking mutex-es.

A mutex is represented by std::mutex class template from a <mutex> header.

A mutex is a way to synchronize access to shared objects between multiple threads.

A thread owns a mutex once it locks the mutex, then performs access to shared data and unlocks the mutex when access to shared data is no longer needed.

This ensures only one thread at the time can have access to a shared object, which is std::cout in our case.

Here is an example where two threads execute the same function and guard access to std::cout object by locking and unlocking mutexes:

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

std::mutex m; // will guard std::cout 

void myfunction(const std::string& param) 
{ 
    for (int i = 0; i < 10; i++) 
    { /*from   w  w  w.  j  a  va2  s .  c o m*/
        m.lock(); 
        std::cout << "Executing function from a " << param << '\n'; 
        m.unlock(); 
    } 
} 

int main() 
{ 
    std::thread t1{ myfunction, "Thread 1" }; 
    std::thread t2{ myfunctiosn, "Thread 2" }; 

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



PreviousNext

Related