-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrwlock.cpp
More file actions
92 lines (74 loc) · 2.52 KB
/
Copy pathrwlock.cpp
File metadata and controls
92 lines (74 loc) · 2.52 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
86
87
88
89
90
91
92
/*
* Copyright (C) 2024 Jimmy Aguilar Mena
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <utils.h>
#include <argparser.hpp>
#include <iostream>
#include "rwlock.hpp"
// Example usage
template <typename T = int>
struct ProtectedData {
ReadWriteLock rwLock;
T sharedData {};
public:
void Read(int id, size_t nReads) {
for (size_t i = 0; i < nReads; ++i) {
rwLock.ReadLock();
std::cout << "Reader " << id << " reads shared data: " << sharedData << std::endl;
rwLock.ReadUnlock();
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
void Write(int id, size_t nWrites) {
for (size_t i = 0; i < nWrites; ++i) {
rwLock.WriteLock();
++sharedData;
std::cout << "Writer " << id << " writes shared data: " << sharedData << std::endl;
std::this_thread::sleep_for(std::chrono::microseconds(10));
rwLock.WriteUnlock();
}
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
operator T() const
{
return sharedData;
}
};
int main(int argc, char **argv) {
argparser::init(argc, argv);
const size_t nWriters = argparser::cl<size_t>("Writers");
const size_t writes = argparser::cl<size_t>("Writes");
const size_t nReaders = argparser::cl<size_t>("nReaders");
const size_t reads = argparser::cl<size_t>("reads");
const size_t maxIts = std::max(nWriters, nReaders);
ProtectedData data;
std::vector<std::thread> readers;
std::vector<std::thread> writers;
for (size_t i = 0; i < maxIts; ++i) {
if (i < nReaders)
readers.emplace_back(&ProtectedData<>::Read, &data, i, reads);
if (i < nWriters)
writers.emplace_back(&ProtectedData<>::Write, &data, i, writes);
}
for (std::thread& reader : readers)
reader.join();
for (std::thread& writer : writers)
writer.join();
std::cout << "Final value: " << data << " expected: " << nWriters * writes << std::endl;
myassert((size_t)data == nWriters * writes);
return 0;
}