When to use C++11 mutex, lock, unique_lock, shared_lock, etc

安稳与你 提交于 2020-12-28 18:33:07

问题


  1. What is the difference between shared_lock and shared_mutex.lock_shared() other than that the destructor of shared_lock unlocks the associated mutex?
  2. Is a shared_mutex the only mutex class I can use with shared_lock?
  3. Why would someone want to use lock_guard instead of unique_lock?
  4. 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?
  5. For #4, is there a possibility for a deadlock?

回答1:


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

  2. No, you can use shared_lock with any type that meets the SharedMutex requirements.

  3. Always use lock_guard unless you need additional functionality of unique_lock. This way your intent is more clear.

  4. 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:

    • On Windows 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.
    • On POSIX systems 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.
    • Boost shared_mutex tries to be fair and gives no preference to either side.
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!