不要等待句柄释放锁,一个线程获得? [英] Do Wait Handles release locks that a thread acquires?

查看:105
本文介绍了不要等待句柄释放锁,一个线程获得?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有code,如下图所示,我的问题是,如果调用signal.WaitOne释放其已经收购了另一个线程获取锁锁的线程?我想这是一个简单的问题要问,但我想寻找这样的事情,来到了空。如果有人可以提供一些线索就这个问题和修改我的职务/职称,使其更可搜索的人在找这个在将来,我会AP preciate它极大地。

 的AutoResetEvent信号=新的AutoResetEvent(假);

富(){
  Monitor.Enter(柜);
  尝试 {
       // code

       如果(条件)
          signal.WaitOne();

       // code
  } 最后 {
      Monitor.Exit(柜);
  }
}
 

编辑:我提出这个编辑以供将来参考:

这似乎是一个更好的模式是什么,我试图做的是这样的:

  FOO(){
  Monitor.Enter(柜);
  尝试 {
       // code

       而(条件)
          Monitor.Wait(柜);

       // code
  } 最后 {
      Monitor.Exit(柜);
  }
}

酒吧 {
  锁(柜){
      Monitor.Pulse(柜);
  }
}
 

解决方案

没有。该锁一直保持到退出被调用。一般来说,你应该尽量不要同时持有一个锁阻塞。它增加了僵局的机会。

When I have code as shown below, my question is if the thread that calls signal.WaitOne release the lock that is has acquired for another thread to acquire the lock? I assume this is a trivial question to ask, but I tried searching for something like this and came up empty. If someone could shed some light on this and modify my post/title to make it more searchable for anyone looking for this in the future, I'd appreciate it greatly.

AutoResetEvent signal = new AutoResetEvent(false);

foo() {
  Monitor.Enter(locker);
  try {
       // code

       if(condition)
          signal.WaitOne();

       // code         
  } finally {
      Monitor.Exit(locker);
  }
}

Edit: I am making this edit for future reference:

It seems like a better paradigm for what I am trying to do is this:

foo() {
  Monitor.Enter(locker);
  try {
       // code

       while(condition)
          Monitor.Wait(locker);

       // code         
  } finally {
      Monitor.Exit(locker);
  }
}

bar {
  lock(locker) {
      Monitor.Pulse(locker);
  }
}

解决方案

No. The lock is held until Exit is called. Generally, you should try not to block while holding a lock. It increases the chances of a deadlock.

这篇关于不要等待句柄释放锁,一个线程获得?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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