CppMem: Locks
This lesson gives an overview of locks used in the context of CppMem.
We'll cover the following...
Both threads - thread1
and thread2
- use the same mutex, and they’re wrapped in a std::lock_guard
.
Press + to interact
// 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 ...