Search⌘ K

CppMem: Locks

Explore the use of locks with std::lock_guard in multithreaded C++ programs using CppMem. Understand how mutexes synchronize threads and affect variable states, while recognizing the limitations and considering more lightweight atomic approaches for concurrency optimization.

We'll cover the following...

Both threads - thread1 and thread2 - use the same mutex, and they’re wrapped in a std::lock_guard.

C++
// ongoingOptimisationLock.cpp
#include <iostream>
#include <mutex>
#include <thread>
int x = 0;
int y = 0;
std::mutex mut;
void writing(){
std::lock_guard<std::mutex> guard(mut);
x = 2000;
y = 11;
}
void reading(){
std::lock_guard<std::mutex> guard(mut);
std::cout << "y: " << y << " ";
std::cout << "x: " << x << std::endl;
}
int main(){
std::thread thread1(writing);
std::thread thread2(reading);
thread1.join();
thread2.join();
};

The program is well-defined. Depending on the execution order (thread1 vs ...