std::shared_mutex
can provide an exclusive lock like std::mutex
. Plus it extends the synchronization capabilities by allowing the parallel read-only accesses to the multiple threads.
Under the hood the number of machine instructions might be lesser for std::mutex
. But at a practical level, while reading about their usage I feel that std::shared_mutex
can potentially supersede or even deprecate std::mutex
.
In other words, is there any place where std::mutex
has to be used over std::shared_mutex
?
Yes
std::shared_mutex
is a powerful synchronization primitive that can be used to implement both read/write locks and exclusive locks which makes it more flexible thanstd::mutex
in many ways.there are still several scenarios wherestd::mutex
would be preferable overstd::shared_mutex
.Performance:
std::mutex
is often simpler and thus faster thanstd::shared_mutex
. Astd::shared_mutex
typically requires more overhead to manage shared access rights. If you don't need the ability to allow multiple simultaneous readers, the simplerstd::mutex
will often be faster.Memory:
std::shared_mutex
can consume more memory thanstd::mutex
due to the extra data needed to manage multiple reader threads.Concurrency Scenario: If the lock is mostly used for writing rather than reading, a simple std::mutex could be preferable since the use case does not really benefit from the
std::shared_mutex
functionality.Complexity:
std::shared_mutex
comes with more operations (lock, try_lock, unlock, lock_shared, try_lock_shared, unlock_shared) which could add unnecessary complexity to the code if only mutual exclusion is required.So,
std::shared_mutex
can offer benefits in terms of allowing multiple readers, if your primary use case is simply to provide exclusive access to a resourcestd::mutex
could still be a simpler and more efficient choice.