11#include <shared_mutex>
30 std::shared_mutex rw_mutex;
31 int shared_resource = 0;
42 std::shared_lock<std::shared_mutex> reader_lock(rw_mutex);
46 std::lock_guard<std::mutex> log(
log_mtx);
47 std::cout <<
"[Reader " << thread_id <<
"] Reading value: " << shared_resource << std::endl;
51 std::this_thread::sleep_for(std::chrono::milliseconds(200));
55 std::lock_guard<std::mutex> log(
log_mtx);
56 std::cout <<
"[Reader " << thread_id <<
"] Finished reading." << std::endl;
69 std::unique_lock<std::shared_mutex> writer_lock(rw_mutex);
72 std::lock_guard<std::mutex> log(
log_mtx);
73 std::cout <<
">>> [Writer " << thread_id <<
"] Writing new value: " << new_data <<
" <<<" << std::endl;
76 shared_resource = new_data;
79 std::this_thread::sleep_for(std::chrono::milliseconds(500));
82 std::lock_guard<std::mutex> log(
log_mtx);
83 std::cout <<
">>> [Writer " << thread_id <<
"] Write complete. <<<" << std::endl;
97 std::vector<std::thread> threads;
101 for(
int i=0; i<=20; i++) {
107 std::this_thread::sleep_for(std::chrono::milliseconds(700));
112 for(
int i=21; i<=30; i++) {
116 for(
int i=31; i<=40; i++) {
120 for(
int i=41; i<=50; i++) {
125 for(
auto& t : threads) {
std::mutex log_mtx
Global mutex to prevent console output interleaving.
int main(void)
Main execution logic.