11 ms·
#include <iostream> #include <mutex> #include <thread> class SharedResource { private: int value; std::mutex mtx; public:
by mrlonglong 11mo ago
#include <iostream>
#include <mutex>
#include <thread>
class SharedResource {
private:
int value;
std::mutex mtx;
public:
SharedResource() : value(0) {}
void setValue(int newValue) {
std::lock_guard<std::mutex> guard(mtx);
value = newValue;
}
int getValue() {
std::lock_guard<std::mutex> guard(mtx);
return value;
}
};
void threadFunction(SharedResource& resource) {
resource.setValue(42);
std::cout << "Value: " << resource.getValue() << std::endl;
}
int main() {
SharedResource resource;
std::thread t1(threadFunction, std::ref(resource));
std::thread t2(threadFunction, std::ref(resource));
t1.join();
t2.join();
return 0;
}
- mrlonglong 11mo agoThis prevents access to the variable being protected by the mutex.