Data Races, Mutexes & std::scoped_lock (C++17)
🔴 Advanced
📖 Definition
A data race occurs when concurrent threads access shared memory simultaneously without synchronization and at least one access is a write. std::mutex (in <mutex>) along with RAII lock guards (std::lock_guard or C++17 std::scoped_lock) guarantees mutually exclusive critical section access.
💡 Code Example
#include <iostream>
#include <thread>
#include <mutex>
int sharedCounter = 0;
std::mutex mtx;
void incrementCounter() {
for (int i = 0; i < 1000; ++i) {
std::scoped_lock lock(mtx); // C++17 RAII deadlock-safe lock
++sharedCounter;
}
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
std::cout << "Synchronized Counter: " << sharedCounter << "\n";
return 0;
}