问题
- What is the difference between
shared_lock
andshared_mutex.lock_shared()
other than that the destructor ofshared_lock
unlocks the associated mutex? - Is a
shared_mutex
the only mutex class I can use withshared_lock
? - Why would someone want to use
lock_guard
instead ofunique_lock
? - If I have many threads constantly locking for reading (
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? - For #4, is there a possibility for a deadlock?
回答1:
shared_mutex.lock_shared()
is a function call that locksshared_mutex
in a shared mode, whileshared_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 ofunique_lock
. This way your intent is more clear.This does not depend on
shared_lock
orunique_lock
, but on whatSharedMutex
you are using. Exact beheavior is not specified by the standard. But here are some clues:- On Windows
shared_lock
will usually be implemented usingSRWLOCK
and tries to be fair e.g. will try to balance readers and writers. No one will have higher priority here. - On POSIX systems
shared_mutex
will most likely be implemented on top ofpthread_rwlock_t
and implementations usually give preference to readers because of its requirement to support recursive read locks. - Boost
shared_mutex
tries to be fair and gives no preference to either side.
- On Windows
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.
来源:https://stackoverflow.com/questions/33770500/when-to-use-c11-mutex-lock-unique-lock-shared-lock-etc