Shared mutex working | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Shared mutex working

Hi C++17 has introduced shared mutex which allows more than one reader thread to read data simultaneously. At a time only one write thread can writes the data to shared resource. This made me think about implementation. As there are 3 threads and none of them has not recieved shared lock to read, writer does not access lock to write.... Is there nothing like reading always take priority and write does not happen at all because three thread are having more chance to block writer by writing.? How to implement this shared mutex as I need to use it in C++11 due to other requirements of solution.

6th Nov 2021, 12:46 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Answers
+ 6
** Generally yes you are correct, any mutex, including reader/writer lock are unfair, which means one thread may never acquire the lock. Yes, you can easily implement reader/writer locks (and just about anything else) using condition variables, which are available in C++11. A rough idea: you have an counter which can be: +ve: number of readers accessing data 0: no one is accessing data -1: writer is accessing data reader_acquire: lock mutex retry_read: counter >=0? Yes: increment counter, release mutex, signal, do work, lock ,decrement counter, unlock, signal No: wait on condition variable, goto retry_read writer_acquire: lock mutex retry_write: counter == 0? Yes: counter = -1, release mutex, do writes, lock, counter = 0, unlock, signal No: wait on condition variable, goto retry_write EDITED! I decided to always have mutex locked when changing counter. To be sure writer gets in, add an extra flag to the condition state "writer waiting". **
6th Nov 2021, 4:39 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 5
NOTE: I edited it so the state changes always occur when hold ing the mutex because I couldn't prove a race wouldn't happen otherwise
6th Nov 2021, 4:41 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 3
I don't know about shared_mutex, but for your need to implement it in C++11, why don't you refer or copy the source code of the shared_mutex thing? I found this while searching for the source code of this. Have a look at it, I think it's worth seeing once https://code.woboq.org/llvm/libcxx/src/shared_mutex.cpp.html
6th Nov 2021, 1:04 PM
Rishi
Rishi - avatar