-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader_writer_lock.cpp
More file actions
64 lines (51 loc) · 1.59 KB
/
reader_writer_lock.cpp
File metadata and controls
64 lines (51 loc) · 1.59 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <mutex> // For std::unique_lock
#include <shared_mutex>
#include <thread>
using namespace std;
class ThreadSafeCounter {
public:
ThreadSafeCounter() = default;
//Notice *shared_lock* for Multiple threads/readers to acces same time.
unsigned int get() const {
std::shared_lock lock(mutex_);
cout << "reader getting counter:" << value_ << std::endl;
return value_;
}
//Notice *unique_lock* for exclusive access.
//Only one thread/writer can increment/write the counter's value.
void increment() {
std::unique_lock lock(mutex_);
cout << "writer updated counter:" << ++value_ << std::endl;
}
// Only one thread/writer can reset/write the counter's value.
void reset() {
std::unique_lock lock(mutex_);
value_ = 0;
}
private:
mutable std::shared_mutex mutex_; //Notice its *shared_mutex*
unsigned int value_ = 0;
};
int main() {
ThreadSafeCounter counter;
auto increment_and_print = [&counter]() {
for (int i = 0; i < 3; i++) {
counter.increment();
std::cout << std::this_thread::get_id() << counter.get() << '\n';
// Note: Writing to std::cout actually needs to be synchronized as well
// by another std::mutex. This has been omitted to keep the example small.
}
};
std::thread thread1(increment_and_print);
std::thread thread2(increment_and_print);
std::thread thread3(increment_and_print);
std::thread thread4(increment_and_print);
std::thread thread5(increment_and_print);
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
return 0;
}