| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 
 | #include <iostream>#include <shared_mutex>
 #include <vector>
 #include <thread>
 
 int sharedData=0;
 std::shared_mutex mySharedMutex;
 
 void readOperation(int id) {
 
 mySharedMutex.lock_shared();
 
 std::cout << "Reader " << id << " reading data: " << sharedData << std::endl;
 mySharedMutex.unlock_shared();
 }
 
 void writeOperation(int id) {
 
 mySharedMutex.lock();
 
 
 sharedData=id;
 std::cout << "Writer " << id << " writing data." << std::endl;
 mySharedMutex.unlock();
 }
 
 int main() {
 std::vector<std::thread> readers;
 std::vector<std::thread> writers;
 
 for (int i = 0; i < 5; ++i) {
 readers.emplace_back(readOperation, i);
 writers.emplace_back(writeOperation, i);
 }
 
 for (auto& reader : readers) {
 reader.join();
 }
 
 for (auto& writer : writers) {
 writer.join();
 }
 
 return 0;
 }
 
 
 |