-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathdemo19b-read-write-lock.cpp
More file actions
85 lines (54 loc) · 1.5 KB
/
Copy pathdemo19b-read-write-lock.cpp
File metadata and controls
85 lines (54 loc) · 1.5 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
READ-WRITE LOCKS
*/
#include <iostream>
#include <numeric>
#include <chrono>
#include <thread>
#include <shared_mutex>
#include "mylib-random.hpp"
using namespace std;
volatile int resource = 0;
auto rwmut = std::shared_mutex();
void readFunc(int waitTime) {
std::this_thread::sleep_for(std::chrono::seconds(waitTime));
std::shared_lock lk(rwmut);
cout << "read: " << resource << endl;
// lk.unlock();
}
void writeFunc(int waitTime) {
std::this_thread::sleep_for(std::chrono::seconds(waitTime));
std::lock_guard lk(rwmut);
// std::unique_lock lk(rwmut);
resource = mylib::RandInt::get(100);
cout << "write: " << resource << endl;
// lk.unlock();
}
int main() {
constexpr int NUM_THREADS_READ = 10;
constexpr int NUM_THREADS_WRITE = 4;
constexpr int NUM_ARGS = 3;
std::thread lstThRead[NUM_THREADS_READ];
std::thread lstThWrite[NUM_THREADS_WRITE];
int lstArg[NUM_ARGS];
// INITIALIZE
// lstArg = { 0, 1, 2, ..., NUM_ARG - 1 }
std::iota(lstArg, lstArg + NUM_ARGS, 0);
// CREATE THREADS
for (auto&& th : lstThRead) {
int arg = lstArg[ mylib::RandInt::get(NUM_ARGS) ];
th = std::thread(&readFunc, arg);
}
for (auto&& th : lstThWrite) {
int arg = lstArg[ mylib::RandInt::get(NUM_ARGS) ];
th = std::thread(&writeFunc, arg);
}
// JOIN THREADS
for (auto&& th : lstThRead) {
th.join();
}
for (auto&& th : lstThWrite) {
th.join();
}
return 0;
}