What's the Difference Between Unique_Lock and Shared_Lock in C++

Trying to understand when one might use shared_lock over unique_lock or vice versa. The C++ doc is very cryptic! I'm aware that the general guideline is to use lock_guard over the two if we desire immediate, scoped (or RAII) mutual exclusion.

Does this have something to do with condition_variable? I've seen all three being used with this if I recall correct.

I've seen a question on stack overflow that is similar but avoids answering this question here: ()%20is%20a%20function,the%20end%20of%20the%20scope.

1 Answer

Its pretty simple, really. unique_lock calls lock() on the mutex. shared_lock calls shared_lock().

The difference between them is that shared_lock is designed to support readers in a read/write lock. You can have multiple threads all acquire the shared lock and reading the same data, but if anyone wants to write to the data, they need to use lock to get permission to write to the data.

Which one you should use depends on the pattern you are looking for. There are plenty of times where a read/write lock is desired (which is why the standard includes support for them). There are also times where a simple unique mutex is called for. In general, if reading and writing are meaningful concepts to you, there's a decent chance that a read/write mutex like shared_timed_mutex is the right approach.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest