When multiple threads read and write shared memory concurrently, access must be synchronized using a Mutex (Mutual Exclusion) to protect Critical Sections.
std::lock_guard#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
int sharedCounter = 0;
std::mutex counterMutex; // Mutex protecting sharedCounter
void safeIncrement() {
for (int i = 0; i < 10000; ++i) {
// RAII: Locks mutex in constructor, unlocks deterministically in destructor!
std::lock_guard<std::mutex> lock(counterMutex);
sharedCounter++;
}
}
int main() {
std::vector<std::jthread> workers;
for (int i = 0; i < 10; ++i) {
workers.emplace_back(safeIncrement);
}
workers.clear(); // Waits for all threads to join
std::cout << "Final Safe Counter: " << sharedCounter << "\n"; // Exactly 100,000!
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Spawning threads and worker pools.
High-speed lock-free primitives without mutexes.
Why lock guards use RAII to guarantee unlocking.