问题
- What is the difference between
shared_lockandshared_mutex.lock_shared()other than that the destructor ofshared_lockunlocks the associated mutex? - Is a
shared_mutexthe only mutex class I can use withshared_lock? - Why would someone want to use
lock_guardinstead 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_mutexin a shared mode, whileshared_lockis a "lock-class" that is used to lock and automatically unlock mutex at the end of the scope.No, you can use
shared_lockwith any type that meets the SharedMutex requirements.Always use
lock_guardunless you need additional functionality ofunique_lock. This way your intent is more clear.This does not depend on
shared_lockorunique_lock, but on whatSharedMutexyou are using. Exact beheavior is not specified by the standard. But here are some clues:- On Windows
shared_lockwill usually be implemented usingSRWLOCKand tries to be fair e.g. will try to balance readers and writers. No one will have higher priority here. - On POSIX systems
shared_mutexwill most likely be implemented on top ofpthread_rwlock_tand implementations usually give preference to readers because of its requirement to support recursive read locks. - Boost
shared_mutextries to be fair and gives no preference to either side.
- On Windows
With reader-preferring
shared_mutexit 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