#include <iostream>
#include <thread>
#include <shared_mutex>
#include <vector>
#include <chrono>
std::shared_mutex sharedMutex;
int sharedResource = 0;
void reader(int id) {
for (int i = 0; i < 5; ++i) {
std::shared_lock<std::shared_mutex> lock(sharedMutex); // Acquire shared (read) lock
std::cout << "Reader " << id << " read value: " << sharedResource << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Simulate work
}
}
void writer(int id) {
for (int i = 0; i < 5; ++i) {
std::unique_lock<std::shared_mutex> lock(sharedMutex); // Acquire unique (write) lock
++sharedResource;
std::cout << "Writer " << id << " updated value to: " << sharedResource << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(150)); // Simulate work
}
}
int main() {
std::vector<std::thread> threads;
// Start several reader threads
for (int i = 0; i < 3; ++i) {
threads.push_back(std::thread(reader, i + 1));
}
// Start a writer thread
threads.push_back(std::thread(writer, 1));
// Join all threads
for (auto& thread : threads) {
thread.join();
}
return 0;
}