我對併發編程有點新,並試圖理解使用Monitor.Pulse和Monitor.Wait的好處。什麼是Monitor.Pulse和Monitor.Wait的優點?
MSDN的例子如下:
class MonitorSample
{
const int MAX_LOOP_TIME = 1000;
Queue m_smplQueue;
public MonitorSample()
{
m_smplQueue = new Queue();
}
public void FirstThread()
{
int counter = 0;
lock(m_smplQueue)
{
while(counter < MAX_LOOP_TIME)
{
//Wait, if the queue is busy.
Monitor.Wait(m_smplQueue);
//Push one element.
m_smplQueue.Enqueue(counter);
//Release the waiting thread.
Monitor.Pulse(m_smplQueue);
counter++;
}
}
}
public void SecondThread()
{
lock(m_smplQueue)
{
//Release the waiting thread.
Monitor.Pulse(m_smplQueue);
//Wait in the loop, while the queue is busy.
//Exit on the time-out when the first thread stops.
while(Monitor.Wait(m_smplQueue,1000))
{
//Pop the first element.
int counter = (int)m_smplQueue.Dequeue();
//Print the first element.
Console.WriteLine(counter.ToString());
//Release the waiting thread.
Monitor.Pulse(m_smplQueue);
}
}
}
//Return the number of queue elements.
public int GetQueueCount()
{
return m_smplQueue.Count;
}
static void Main(string[] args)
{
//Create the MonitorSample object.
MonitorSample test = new MonitorSample();
//Create the first thread.
Thread tFirst = new Thread(new ThreadStart(test.FirstThread));
//Create the second thread.
Thread tSecond = new Thread(new ThreadStart(test.SecondThread));
//Start threads.
tFirst.Start();
tSecond.Start();
//wait to the end of the two threads
tFirst.Join();
tSecond.Join();
//Print the number of queue elements.
Console.WriteLine("Queue Count = " + test.GetQueueCount().ToString());
}
}
,我不能看到使用等待的好處,而是脈衝這樣的:
public void FirstThreadTwo()
{
int counter = 0;
while (counter < MAX_LOOP_TIME)
{
lock (m_smplQueue)
{
m_smplQueue.Enqueue(counter);
counter++;
}
}
}
public void SecondThreadTwo()
{
while (true)
{
lock (m_smplQueue)
{
int counter = (int)m_smplQueue.Dequeue();
Console.WriteLine(counter.ToString());
}
}
}
任何幫助最讚賞。 謝謝
嘿,謝謝你的快速回復。 關於什麼問題 - 結束使用Monitor.Enter和Monitor.Exit, 我真的不知道Pulse和Wait的差別如何比使用這兩種方法 - 只是在性能成本方面。 – seren1ty
@ seren1ty他們完全***不同的事情;進入/退出獲取並釋放一個鎖;等待釋放鎖,進入等待隊列(等待脈衝),然後(當喚醒時)重新獲得鎖; Pulse將等待的項目從等待隊列移動到就緒隊列。 ***完全不同(但免費)使用。脈衝/等待用於*線程之間的座標*,而不需要熱循環或冷循環。 –