difference between std::mutex and std::shared_mutex

后端 未结 3 2026
半阙折子戏
半阙折子戏 2021-02-07 08:27

I came across an std::shared_mutex in C++17. what exactly is std::shared_mutex and how it is different from std::mutex?

3条回答
  •  猫巷女王i
    2021-02-07 09:04

    As noted in the documentation

    The shared_mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads. In contrast to other mutex types which facilitate exclusive access, a shared_mutex has two levels of access:

    • shared - several threads can share ownership of the same mutex.
    • exclusive - only one thread can own the mutex.

    Shared mutexes are usually used in situations when multiple readers can access the same resource at the same time without causing data races, but only one writer can do so.

    This has a variety of uses, but one common one is to implement a Read Write Lock where you could have multiple threads reading shared data, but only one thread exclusively writing at any time. So when you have multiple readers the mutex acts in "shared mode", but when a write is requested it changes into "exclusive mode".

提交回复
热议问题