Manages a shared resource with high-concurrency read access.
More...
|
| void | read_data (int thread_id) |
| | Reads the shared data concurrently.
|
| |
| void | write_data (int thread_id, int new_data) |
| | Updates the shared data exclusively.
|
| |
Manages a shared resource with high-concurrency read access.
- Uses std::shared_mutex to solve the Readers-Writers problem.
- Readers use std::shared_lock (shared ownership).
- Writers use std::unique_lock (exclusive ownership).
Definition at line 28 of file ReaderWriterLock.cpp.
◆ read_data()
| void SharedMetaData::read_data |
( |
int |
thread_id | ) |
|
|
inline |
Reads the shared data concurrently.
- Multiple reader threads can execute this method at the same time, provided no writer holds an exclusive lock.
- Parameters
-
| thread_id | Unique identifier for the reader thread. |
Definition at line 40 of file ReaderWriterLock.cpp.
40 {
41
42 std::shared_lock<std::shared_mutex> reader_lock(rw_mutex);
43
44 {
45
46 std::lock_guard<std::mutex> log(
log_mtx);
47 std::cout << "[Reader " << thread_id << "] Reading value: " << shared_resource << std::endl;
48 }
49
50
51 std::this_thread::sleep_for(std::chrono::milliseconds(200));
52
53 {
54
55 std::lock_guard<std::mutex> log(
log_mtx);
56 std::cout << "[Reader " << thread_id << "] Finished reading." << std::endl;
57 }
58 }
std::mutex log_mtx
Global mutex to prevent console output interleaving.
References log_mtx.
Referenced by main().
◆ write_data()
| void SharedMetaData::write_data |
( |
int |
thread_id, |
|
|
int |
new_data |
|
) |
| |
|
inline |
Updates the shared data exclusively.
- Blocks all incoming readers and waits for existing readers to finish before modifying the shared_resource.
- Parameters
-
| thread_id | Unique identifier for the writer thread. |
| new_data | The new value to store in the resource. |
Definition at line 67 of file ReaderWriterLock.cpp.
67 {
68
69 std::unique_lock<std::shared_mutex> writer_lock(rw_mutex);
70
71 {
72 std::lock_guard<std::mutex> log(
log_mtx);
73 std::cout << ">>> [Writer " << thread_id << "] Writing new value: " << new_data << " <<<" << std::endl;
74 }
75
76 shared_resource = new_data;
77
78
79 std::this_thread::sleep_for(std::chrono::milliseconds(500));
80
81 {
82 std::lock_guard<std::mutex> log(
log_mtx);
83 std::cout << ">>> [Writer " << thread_id << "] Write complete. <<<" << std::endl;
84 }
85 }
References log_mtx.
Referenced by main().
The documentation for this class was generated from the following file: