Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can thread trying to std::lock[_unique] an std::shared_mutex be starved by threads calling std::lock_shared?

A question regarding std::shared_mutex and the acquiring of unique_lock.

Assume there are 3 threads:

  • 2 readers (trying to lock_shared() the std::shared_mutex), and
  • 1 writer (trying to 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)

like image 529
hauron Avatar asked Aug 27 '15 07:08

hauron


1 Answers

More or less: would lock[_unique]() on a std::shared_mutex block any attempts to further lock_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.

like image 187
Jonathan Wakely Avatar answered Sep 18 '22 17:09

Jonathan Wakely