两个对象上的 SyncLock
假设我有两个对象a和b。
我想在两个对象上同步锁定。
这可行吗?可以通过嵌套SyncLock语句来完成吗?这样的操作有什么危险?
编辑
也许我应该问,如何重构才能避免死锁?
Suppose I have two objects a and b.
I want to SyncLock on both objects.
Is this feasible? Can it be done by nested SyncLock statements? What are the dangers of such an operation?
Edit
Perhaps I should ask, how can one refactor to avoid deadlocks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嵌套锁可以工作,但是危险之一是需要始终以相同的顺序锁定对象,否则可能会导致死锁。
编辑:
要回答有关尝试强制正确的锁顺序的第二个问题:
避免这种情况的可能解决方案可能是将锁定封装到一个常见的锁方法中,如下所示:
然后可以这样使用:
这可以帮助避免这种潜在问题 -如果可以限制客户端代码对这些对象的可见性,这将特别有用
Nested locks will work - however one of the dangers is that one needs to always lock the objects in the same order, else one could cause a deadlock.
EDIT:
To answer the second question around trying force the correct order of locks:
A possible solution to avoid this might be to encapsulate the locking into a common lock method like this:
This could then be used like this:
This can help avoid this potential issue - it's especially useful if one can limit visibility to those objects from client code
按照严格的优先级顺序定义所有同步锁,并且始终首先采用最高优先级。
这很困难:当持有较低优先级锁的一个代码块可能调用需要获取较高优先级锁的帮助程序代码时,将需要进行重大重构。
Defining all sync locks in a strong order of priority and always taking the highest priority first.
This is hard: when one code block holding a lower priority lock could call into helper code that needs to take a higher priority lock significant refactoring will be needed.
这是可能的,但您需要考虑如果运行此代码的 2 个线程尝试同时获取两个锁会发生什么情况 - 例如,如果线程 1 拥有对象 1 上的锁,而线程 2 拥有对象 2 上的锁?提示僵局。
比我更好的人可以给你一些应该安全的示例代码:)
It's possible to do but you need to consider what happens if 2 threads running this code try to get both locks at the same time - eg if thread 1 has a lock on object 1 and thread 2 has a lock on object 2? Cue deadlock.
Someone better than I can give you some example code that should be safe :)