std :: mutex和std :: shared_mutex之间的区别 [英] difference between std::mutex and std::shared_mutex

查看:1078
本文介绍了std :: mutex和std :: shared_mutex之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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_mutex类是一个同步原语,可用于保护共享数据不被多个线程同时访问.与其他有助于互斥访问的互斥锁类型相比,shared_mutex具有两种访问级别:

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

这篇关于std :: mutex和std :: shared_mutex之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆