A question regarding std::shared_mutex
and the acquiring of unique_lock
.
Assume there are 3 threads:
lock_shared()
the std::shared_mutex
), and lock[_unique]()
the std::shared_mutex
)Is it possible that the writer trying to lock[_unique]()
would be starved? E.g.: at all times at least one reader owns a std::shared_lock
, and lock[_unique]()
can never succeed.
More or less: would lock[_unique]()
on a std::shared_mutex
block any attempts to further lock_shared()
it?
(pretty sure boost::upgrade_lock
could work here, but I'd like to know if there's any guarantee for bare std::unique_lock
on a std::shared_mutex
)
More or less: would
lock[_unique]()
on astd::shared_mutex
block any attempts to furtherlock_shared()
it?
The standard doesn't specify whether that should happen or not, it only says:
Effects: Blocks the calling thread until shared ownership of the mutex can be obtained for the calling thread.
So it's left up to the implementation whether it makes later readers wait behind pending writers or not.
If the implementation wants to prevent writer starvation then it might need to have a "writer waiting" flag that is set when a thread tries to obtain a unique lock, so that later attempts to get a shared lock will block, waiting behind the unique locker. In the N2406 reference implementation this is the write_entered_
bit in the state
member.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With