Medium
A std::shared_mutex writer waiting behind a continuous reader stream
A single writer thread calls tryUpdate() once and blocks waiting for the unique_lock. Meanwhile, a steady, overlapping stream of new reader threads keeps arriving, each taking and releasing a shared_lock quickly, such that at least one reader is essentially always holding the lock in shared mode. What is guaranteed to eventually happen to the writer?
main.cpp
std::shared_mutex rw;
int sharedValue = 0;
void reader() {
while (true) {
std::shared_lock<std::shared_mutex> lock(rw);
int v = sharedValue; // brief read
(void)v;
}
}
void tryUpdate() {
std::unique_lock<std::shared_mutex> lock(rw); // waiting to acquire exclusive access
sharedValue++;
}33 of 51 in Concurrency