条件变量模式(The Condition variable Pattern)
指的是一个任务在等待一个变量的状态.(例如一个线程当变量为true的时候执行,否则就一直在休眠状态)
以下代码演示了Thread1 一直在等待m_condition的状态
Thread1在等待状态改变的过程中,间歇性的暂时释放锁的控制权
这样Thread2就有机会获得到锁,改变m_condition的状态,并且执行Pulse(All)方法, 该方法将在执行Mointor.Exit(m_lock)的时候唤醒所有等待者,此时等待者发现状态已经改变,那么就开始执行相应的业务逻辑
代码
internal sealed class ConditionVariablePattern { private readonly Object m_lock = new Object(); private Boolean m_condition = false; public void Thread1() { Monitor.Enter(m_lock); // Acquire a mutual-exclusive lock // While under the lock, test the complex condition "atomically" while (!m_condition) { // If condition is not met, wait for another thread to change the condition Monitor.Wait(m_lock); // Temporarily release lock so other threads can get it } // The condition was met, process the data... Monitor.Exit(m_lock); // Permanently release lock } public void Thread2() { Monitor.Enter(m_lock); // Acquire a mutual-exclusive lock // Process data and modify the condition... m_condition = true; // Monitor.Pulse(m_lock); // Wakes one waiter AFTER lock is released Monitor.PulseAll(m_lock); // Wakes all waiters AFTER lock is released Monitor.Exit(m_lock); // Release lock } }
这个模式的好处就是不像自旋锁(Spin Lock)一样在等待的过程中浪费cpu
自旋锁通常用于非常短时间的锁定, 如果长时间锁定将大量浪费cpu
所以稍微长的时间锁定可以采用条件变量模式
PS1:如果....如果没人吧条件置为许可的状态...那么这线程就永远等下去了..直到进程被终止的那一天
|
请发表评论