Search⌘ K

Introduction to Mutexes

Explore how mutexes in C++ provide mutual exclusion to protect shared data and prevent race conditions during concurrent thread access. Understand the concept of critical sections and how locking mechanisms control thread synchronization for safer multithreading.

We'll cover the following...

Mutex stands for mutual exclusion. It ensures that only one thread can access a critical section at any one time. By using a mutex, the mess of the workflow turns into harmony.

C++
// coutSynchronised.cpp
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
std::mutex coutMutex;
class Worker{
public:
Worker(std::string n):name(n){};
void operator() (){
for (int i = 1; i <= 3; ++i){
// begin work
std::this_thread::sleep_for(std::chrono::milliseconds(200));
// end work
coutMutex.lock();
std::cout << name << ": " << "Work " << i << " done !!!" << std::endl;
coutMutex.unlock();
}
}
private:
std::string name;
};
int main(){
std::cout << std::endl;
std::cout << "Boss: Let's start working." << "\n\n";
std::thread herb= std::thread(Worker("Herb"));
std::thread andrei= std::thread(Worker(" Andrei"));
std::thread scott= std::thread(Worker(" Scott"));
std::thread bjarne= std::thread(Worker(" Bjarne"));
std::thread bart= std::thread(Worker(" Bart"));
std::thread jenne= std::thread(Worker(" Jenne"));
herb.join();
andrei.join();
scott.join();
bjarne.join();
bart.join();
jenne.join();
std::cout << "\n" << "Boss: Let's go home." << std::endl;
std::cout << std::endl;
}

Essentially, when the lock is set on a mutex, no other thread can access the locked region of code. In other words, lines ...