example1_shared_resource.cpp

 1
 2
 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
#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;
}
Back to std_shared_mutex