多个代码块被同一对象锁定
如果我有这样的事情:
private readonly object objectLock = new object();
public void MethodA()
{
lock(objectLock)
{
//do something
}
}
public void MethodB()
{
lock(objectLock)
{
//do something
}
}
如果我有 2 个线程并且同时进入,第一个线程调用 MethodA 和第二个方法 B。无论哪个线程先到达那里并锁定 objectLock,我假设另一个线程坐在那里等待,直到 objectLock 为 no锁定时间更长。
If I have something like this:
private readonly object objectLock = new object();
public void MethodA()
{
lock(objectLock)
{
//do something
}
}
public void MethodB()
{
lock(objectLock)
{
//do something
}
}
If I have 2 threads and both come in at the same time, 1st thread calls MethodA and second Method B. Whichever gets there first and locks objectLock, I assume the other thread sits there waiting until objectLock is no longer locked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,你的解释是正确的——除非锁已经被占用(在这种情况下,两个线程都在等待,并且任意一个线程在解锁后立即获得锁)。
(有点离题)我建议如果他们正在做一些不平凡的事情,不要锁定整个方法。尝试使代码的“锁定”部分尽可能小且尽可能快。
Yes, your explanation is right -- unless the lock is already taken (in which case both threads sit waiting, and an arbitrary one gets the lock as soon as it's unlocked).
(Slightly offtopic) I would advise not to lock the whole methods if they are doing something non-trivial. Try to keep the "locking" section of code as small and as fast as possible.
这是正确的。
然而,被锁定的不是 objectLock(也不是对象),而是被锁定的代码块。
将传递给
lock
关键字的对象视为一把钥匙,它可以解锁多扇门,但一次只能授予对单个房间的访问权限。That is correct.
However it is not the objectLock that is locked (nor the object) it is the code blocks that are locked.
Think of the object that is passed to the
lock
keyword as a key that does unlock multiple doors but only grants access to a single room at one time.你说得完全正确!但要小心锁。锁可能会使您的程序线程安全(意味着并发访问时不会出现错误),但是要使您的程序真正从在多内核系统上运行中获益需要付出更多的努力。
You're absolutely right! But be careful with locks. Locks will maybe make you're program thread-safe (means, no errors on concurrent accesses) but it takes much more effort making make your program taking real advantage from running on a multi-kernel system.
是的,你是对的,因为 Monitor.Enter 和 Monitor.Exit 在场景后面的同一对象 objectLock 上被调用。记住它是同步的代码块而不是objectLock。
yes you are right as Monitor.Enter and Monitor.Exit is called on same object objectLock behind the scene. remember its the code block that is synchronized not the objectLock.
你是对的。如果这不可取,请考虑:
相当于:
您可以将其替换为:
还值得查看
TryEnter()
的重载以及其他同步对象,例如ReaderWriterLockSlim
。You're correct. If this isn't desirable, then consider that:
Is equivalent to:
You can replace this with:
It's also worth looking at the overloads of
TryEnter()
, and the other synchronisation objects such asReaderWriterLockSlim
.