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

问题描述

大家好,

Hello everyone,


这里是有关何时使用Pulse以及何时使用PulseAll以获得最佳性能的说明.


Here is the description about when to use Pulse and when to use PulseAll to achieve best performance.

我的问题是,我对这种情况不太了解,有时,不同的线程在不同的条件下等待,但所有线程都在同一监视器上等待.在那种情况下,您需要使用PulseAll,以确保正在等待刚刚发生的任何情况的线程都能注意到它并取得进展.任何人都可以显示一个场景的意思是什么意味着不同的线程在不同的条件下等待,但所有线程都在同一监视器上等待".请吗?

My question is, I do not quite understand this situation, "Sometimes, however, different threads are waiting on different conditions, but all waiting on the same monitor. In that case, you need to use PulseAll so that you make sure that the thread which is waiting for whatever condition has just occurred is able to notice it and make progress."? Could anyone show a scenario about what means "different threads are waiting on different conditions, but all waiting on the same monitor" please?

(下面引用了链接和相关的整个段落)

(the link and related whole paragraph is quoted below)

--------------------
同时使用Pulse和PulseAll的原因是针对不同的情况,即您在不同的条件下等待.如果只有一个线程在等待,或者(如上所述)任何线程都可以使用任何产生的对象,则可以使用Pulse.如果有多个线程在对象上等待,那最终将比PulseAll效率更高-如果您知道只有一个线程能够取得进展,那么唤醒一堆线程是没有意义的,并且它不会不管你醒来是什么.但是,有时,不同的线程在不同的条件下等待,但所有线程都在同一监视器上等待.在这种情况下,您需要使用PulseAll,以确保正在等待刚刚发生的任何情况的线程都能注意到它并取得进展.
--------------------

--------------------
The reason for having both Pulse and PulseAll is for different situations, where you're waiting on different conditions. If either there'll only be one thread waiting, or (as is the case above) any thread can consume any produced object, you can just use Pulse. If there are several threads waiting on the object, that ends up being more efficient than PulseAll - there's no point in waking up a bunch of threads if you know that only one of them is going to be able to make progress, and that it doesn't matter which you wake up. Sometimes, however, different threads are waiting on different conditions, but all waiting on the same monitor. In that case, you need to use PulseAll so that you make sure that the thread which is waiting for whatever condition has just occurred is able to notice it and make progress.
--------------------


先谢谢了,
George


thanks in advance,
George

推荐答案

的代码
私有 对象 m_Monitor == Object();
私有 布尔 m_Condition1 == false ;
私有 无效 ThreadProc()
.{
( true )
.{
(m_Monitor)
.{
(!m_Condition1)
.{
Monitor.Wait(m_Monitor);
//如果执行在此处,我们将锁定在m_Monitor
//和m_Condition1是真实的.执行
//要求m_Condition1在此处为真.
    private object m_Monitor = new Object();  
    private bool m_Condition1 = false;  
 
    private void ThreadProc()  
    {  
      while (true)  
      {  
        lock (m_Monitor)  
        {  
          while (!m_Condition1)  
          {  
            Monitor.Wait(m_Monitor);  
          }  
 
          // If execution gets here, we hold the lock on m_Monitor  
          // and m_Condition1 is true. Execute the code that  
          // requires m_Condition1 to be true here.  
        }  
      }  
    } 


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

10-25 06:11