Search code examples
c++multithreadingmutex

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 correctly.

I've seen a question on stack overflow that is similar but avoids answering this question here: When to use C++11 mutex, lock, unique_lock, and shared_lock?


Solution

  • 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.