1 /// <summary>2 ///Conditional Variable Mode3 ///let threads execute on condition4 /// </summary>5 Public Sealed classConditionvariablepattern6 {7 //two threads using the same lock8 Private ReadOnly ObjectM_lock =New Object();9 Ten //Compound condition (here is just a simple Boolean type) One Private BOOLM_condition =false; A - Public voidThread1 () - { the //acquires an exclusive lock on the specified object - Monitor.Enter (m_lock); - - //Test compound condition of atomicity in lock + //when conditions are not met - while(!m_condition) + { A //temporarily releases the lock so that other threads can get it at //wait for another thread to change the condition - //releases the lock on the object and blocks the current thread until it acquires the lock again - monitor.wait (m_lock); - } - - //come here to show that the conditions are met and can handle their own business in - //Permanent release Lock to Monitor.Exit (m_lock); + } - the Public voidThread2 () * { $ //get a mutex lockPanax Notoginseng Monitor.Enter (m_lock); - the //Process Business data, modify conditions +M_condition =true; A the //unblocking threads may waste some CPU time + //notifies a thread in the waiting queue of a change in the lock object state - //A waiting thread is awakened after the lock is released $ //Monitor.pulse (m_lock); $ - //unblocking threads may waste some CPU time - //notifies all waiting thread object states of Changes the //wake up all waiting threads after the lock is released - Monitor.pulseall (m_lock);Wuyi the //Release Lock - Monitor.Exit (m_lock); Wu } -}
Conditional variable mode-lets threads perform according to conditions