gpt4 book ai didi

multithreading - 什么时候或为什么我应该使用 Mutex 而不是 RwLock?

转载 作者:行者123 更新时间:2023-11-29 07:42:29 25 4
gpt4 key购买 nike

当我阅读 Mutex 的文档时和 RwLock ,我看到的区别如下:

  • Mutex 一次只能有一个读取器或写入器,
  • RwLock 一次可以有一个写入器或多个读取器。

当你这么说时,RwLock 似乎总是比 Mutex 更好(限制更少),那么我为什么要使用它呢?

最佳答案

有时最好使用 MutexRwLock在 Rust 中:

RwLock<T> T 需要更多边界线程安全:

换句话说,Mutex是唯一可以制作 T 的包装器可同步。我找到了一个 good and intuitive explanation在 reddit 中:

Because of those bounds, RwLock requires its contents to be Sync, i.e. it's safe for two threads to have a &ptr to that type at the same time. Mutex only requires the data to be Send, because conceptually you can think of it like when you lock the Mutex it sends the data to your thread, and when you unlock it the data gets sent to another thread.

使用 Mutex当你的 T只有Send而不是 Sync .

防止写入器饥饿

RwLock没有指定的实现,因为它使用系统的实现。一些读写锁可能受制于 writer starvation同时 Mutex不能有这种问题。

Mutex当您可能有太多读者而无法让作者获得锁时,应使用此方法。

关于multithreading - 什么时候或为什么我应该使用 Mutex 而不是 RwLock?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50704279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com