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

前端 未结 1 630
梦谈多话
梦谈多话 2021-02-05 19:35
  1. What is the difference between shared_lock and shared_mutex.lock_shared() other than that the destructor of shared_lock unlocks the
1条回答
  •  余生分开走
    2021-02-05 20:29

    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.

    0 讨论(0)
提交回复
热议问题