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_mutexis a powerful synchronization primitive that can be used to implement both read/write locks and exclusive locks which makes it more flexible thanstd::mutexin many ways.there are still several scenarios wherestd::mutexwould be preferable overstd::shared_mutex.Performance:
std::mutexis often simpler and thus faster thanstd::shared_mutex. Astd::shared_mutextypically requires more overhead to manage shared access rights. If you don't need the ability to allow multiple simultaneous readers, the simplerstd::mutexwill often be faster.Memory:
std::shared_mutexcan consume more memory thanstd::mutexdue 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_mutexfunctionality.Complexity:
std::shared_mutexcomes 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_mutexcan offer benefits in terms of allowing multiple readers, if your primary use case is simply to provide exclusive access to a resourcestd::mutexcould still be a simpler and more efficient choice.