ReaderWriterLock 如何在线程之间共享?是用单例实现的吗?
当你想使用 ReaderWriterLock 时,你可以这样声明它:
ReaderWriterLock rwLock = new ReaderWriterLock;
好吧,如果你要为所有要访问某些内容的不同线程执行此操作,您想要保护的资源,它们(大概)都使用不同的 ReaderWriterLock 实例。
ReaderWriterLock实例如何在线程之间共享?
另外,作为奖励,有人可以帮我确认一下您真正“锁定”的是 ReaderWriterLock 状态,而不是任何资源。与 lock(someResourceToLock)
不同,除了 ReaderWriterLock 实例的状态(无论是处于读取模式还是写入模式,以及是否允许您读取和写入)之外,您不会锁定任何其他内容。
When you want to use a ReaderWriterLock
you declare it like this:
ReaderWriterLock rwLock = new ReaderWriterLock;
Well if you are doing that for all your different threads that are going to access some resource that you want to protect, they (presumably) are all using differnt ReaderWriterLock instances.
How is the ReaderWriterLock instance shared amongs threads?
Also, as a bonus, can someone confirm for me that what you are really "locking" is the ReaderWriterLock state, not any resource. Unlike lock(someResourceToLock)
, you aren't locking anything but the ReaderWriterLock instance's state (whether it is in read or write mode, and whether you are allowed to read and write yet).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用
ReaderWriterLock rwLock = new ReaderWriterLock
每个线程或每个方法(即作为方法变量),那么您的代码最-可能坏了。它不是一个单例;它依赖于使用相同锁访问受保护数据的所有线程。这通常是通过将锁放置在字段中来实现的,即在许多情况下也可以考虑 ReaderWriterLockSlim ;更少的开销。重新跟进;当获取锁时,您正在更改内部状态(以线程安全的方式)以保留“多读取器
nand
单写入器”期望(可能会阻塞,直到可能,即冲突的锁已已撤回)。If you are using the
ReaderWriterLock rwLock = new ReaderWriterLock
per thread or per method (i.e. as a method variable), then your code is most-likely broken. It is not a singleton; it relies on all threads accessing the protected data using the same lock. This is most commonly achieved by placing the lock in a field, i.e.Also - maybe consider
ReaderWriterLockSlim
in many scenarios; less overhead. Re your follow-up; when acquiring the lock you are changing the internal state (in a thread-safe manner) to preserve the "many-readersnand
single-writer" expectation (perhaps blocking until that is possible, i.e. conflicting locks have been withdrawn).创建
的单个实例ReaderWriterLock
并在访问您想要保护的共享资源的所有线程中使用它。您实际上正在锁定。
lock(obj) { ... }
只是一个捷径(这里进行了简化,真正的实现有一些额外的微妙之处来处理边缘情况):在每个引用类型中使用字段来保存状态由
监视器
使用。正如 Marc 指出的那样,请考虑
ReaderWriterLockSlim
除非您需要公平性(保证线程按照开始等待的顺序进入)ReaderWriterLock
给出。Create a single instance of
ReaderWriterLock
and use it from all threads that are accessing the shared resource you want to protect.You really are locking.
lock(obj) { ... }
is just a short cut for (simplified here, the real implementation has some additional subtleties to handle edge cases):using the field in every reference type to hold the state used by
Monitor
.As Marc notes, consider
ReaderWriterLockSlim
unless you need the fairness (threads guaranteed to enter in the order they starting waiting) thatReaderWriterLock
gives.