问题描述
我在C++17
中碰到了std::shared_mutex
. std::shared_mutex
到底是什么?它与std::mutex
有何不同?
I came across an std::shared_mutex
in C++17
. what exactly is std::shared_mutex
and how it is different from std::mutex
?
推荐答案
如文档
- 共享-多个线程可以共享同一个互斥锁的所有权.
- 专有-只有一个线程可以拥有互斥体.
- 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".
这篇关于std :: mutex和std :: shared_mutex之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!