iammilind
iammilind

Reputation: 70078

Is `std::shared_mutex` virtually a superset of `std::mutex`?

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?

Upvotes: 0

Views: 197

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474236

std::vector is a functional superset of std::array. Anything an array can do, a vector can do as well.

But that's not a good excuse to avoid using array when it is obviously appropriate (ie: statically sized, no need for heap allocation, etc).

Likewise, shared_mutex could be used in any place that mutex could. But that doesn't mean you should.

The types you use communicates something to the people who read your code. If you use shared_ptr, you are communicating to users that ownership of this object is being shared. That's what the name means. Using shared_ptr when you only use it for unique ownership of a resource says either that you expect to share it in the future or you don't know what you're doing.

Using shared_mutex communicates that users are expected to acquire shared locks to this mutex. This says something about the access patterns of code trying to access the guarded data. It means that the data will be read concurrently by a lot of code, but will only occasionally need exclusive access by some restricted subset of code.

And as with shared_ptr, using it in cases where this does not happen is a miscommunication of what is going on in your code.

And that ignores the performance implications. shared_mutex and its locks aren't free, after all. Any "practical level" should not throw performance away.

Upvotes: 3

Related Questions