shared_lock
and shared_mutex.lock_shared()
other than that the destructor of shared_lock
unlocks the associated mutex?shared_mutex
the only mutex class I can use with shared_lock
?lock_guard
instead of unique_lock
?shared_lock
) a variable and I have a variable that tries to lock it for writing (unique_lock
), will this writing thread have a priority over the other ones?There are two primary benefits to using std::unique_lock<> over std::lock_guard<> : you can transfer ownership of the lock between instances, and. the std::unique_lock<> object does not have to own the lock on the mutex it is associated with.
A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.
class shared_lock; (since C++14) The class shared_lock is a general-purpose shared mutex ownership wrapper allowing deferred locking, timed locking and transfer of lock ownership. Locking a shared_lock locks the associated shared mutex in shared mode (to lock it in exclusive mode, std::unique_lock can be used)
@Prab, just to give the explanation: unique_lock() is automatically released when the destructor is called meaning it is exception safe and that it automatically unlocks when you leave scope.
shared_mutex.lock_shared()
is a function call that locks shared_mutex
in a shared mode, while shared_lock
is a "lock-class" that is used to lock and automatically unlock mutex at the end of the scope.
No, you can use shared_lock
with any type that meets the SharedMutex requirements.
Always use lock_guard
unless you need additional functionality of unique_lock
. This way your intent is more clear.
This does not depend on shared_lock
or unique_lock
, but on what SharedMutex
you are using. Exact beheavior is not specified by the standard. But here are some clues:
shared_lock
will usually be implemented using SRWLOCK
and tries to be fair e.g. will try to balance readers and writers. No one will have higher priority here.shared_mutex
will most likely be implemented on top of pthread_rwlock_t
and implementations usually give preference to readers because of its requirement to support recursive read locks.shared_mutex
tries to be fair and gives no preference to either side.With reader-preferring shared_mutex
it is possible for your writer thread to never acquire the lock if there is always at least one reader holding it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With