两个对象上的 SyncLock

发布于 2024-09-14 21:08:45 字数 153 浏览 5 评论 0原文

假设我有两个对象ab

我想在两个对象上同步锁定。

这可行吗?可以通过嵌套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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

瘫痪情歌 2024-09-21 21:08:45

嵌套锁可以工作,但是危险之一是需要始终以相同的顺序锁定对象,否则可能会导致死锁。


编辑:
要回答有关尝试强制正确的锁顺序的第二个问题:

避免这种情况的可能解决方案可能是将锁定封装到一个常见的锁方法中,如下所示:

public void LockAndDoWork(Action action)
{
 lock(lockObject1)
 {
  lock(lockObject2)
  {
    action();
  }
 }
}

然后可以这样使用:

Thread1: LockAndDoWork(() => {do some work....});
Thread2: LockAndDoWork(() => {do some other work...});

这可以帮助避免这种潜在问题 -如果可以限制客户端代码对这些对象的可见性,这将特别有用

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:

public void LockAndDoWork(Action action)
{
 lock(lockObject1)
 {
  lock(lockObject2)
  {
    action();
  }
 }
}

This could then be used like this:

Thread1: LockAndDoWork(() => {do some work....});
Thread2: LockAndDoWork(() => {do some other work...});

This can help avoid this potential issue - it's especially useful if one can limit visibility to those objects from client code

谢绝鈎搭 2024-09-21 21:08:45

也许我应该问,如何重构才能避免死锁?

按照严格的优先级顺序定义所有同步锁,并且始终首先采用最高优先级。

这很困难:当持有较低优先级锁的一个代码块可能调用需要获取较高优先级锁的帮助程序代码时,将需要进行重大重构。

Perhaps I should ask, how can one refactor to avoid deadlocks?

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.

缱绻入梦 2024-09-21 21:08:45

这是可能的,但您需要考虑如果运行此代码的 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 :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文