锁内锁 [英] lock inside lock

查看:65
本文介绍了锁内锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这种构造是否会导致错误:

I'm wondering if this construction will cause an error:

lock(sync)
{
  // something
  lock(sync)
  {
    //something
    lock(sync)
    {
      //something
    }
  }
}

我已经运行了这段代码,看起来还不错,但是在某些情况下可能会引发错误?

I've run this code, and it seems fine, but maybe in some circumstances an error may be thrown?

推荐答案

lock是针对Monitor.EnterMonitor.Exit :

lock is a wrapper for Monitor.Enter and Monitor.Exit:

lock关键字在块的开头调用Enter,在块的结尾调用Exit.从前者的文档中:

The lock keyword calls Enter at the start of the block and Exit at the end of the block. From the former's documentation:

Monitor.Enter 的文档中:

From the documentation for Monitor.Enter:

同一线程多次调用Enter而不阻塞它是合法的;但是,必须等待相等数量的Exit调用,然后其他等待该对象的线程才能解除阻塞.

It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.

由于对EnterExit的调用是配对的,因此您的代码模式具有明确的行为.

Because the calls to Enter and Exit are paired, your code pattern has well defined behaviour.

但是请注意,不能保证lock是无异常的构造:

Note, however, that lock is not guaranteed to be an exception-less construct:

如果Interrupt中断正在等待输入lock语句的线程,则会抛出ThreadInterruptedException.

A ThreadInterruptedException is thrown if Interrupt interrupts a thread that is waiting to enter a lock statement.

这篇关于锁内锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆