मैं समवर्ती प्रोग्रामिंग के लिए नया हूं, और मॉनिटर.पल्स और मॉनिटर.एट का उपयोग करने के लाभों को समझने की कोशिश कर रहा हूं।मॉनिटर.पल्स और मॉनीटर क्या हैं। प्रतीक्षा करें?
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());
}
}
और मैं नहीं कर सकते प्रतीक्षा उपयोग करने का लाभ देखना और यह करने के बजाय पल्स:
MSDN के उदाहरण का पालन करना है
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());
}
}
}
कोई मदद सबसे की सराहना की है। धन्यवाद
हे, त्वरित उत्तर के लिए धन्यवाद। मॉनिटर.इंटर और मॉनिटर.एक्सिट, का उपयोग करने पर पर सवाल के बारे में क्या है, मैं वास्तव में नहीं देखता कि कैसे पल्स और प्रतीक्षा इन दो विधियों का उपयोग करने से बहुत अलग है - केवल प्रदर्शन लागत के संदर्भ में। – seren1ty
@ seren1ty वे *** पूरी तरह से *** अलग-अलग चीजें करते हैं; एंटर करें/बाहर निकलें और लॉक जारी करें; प्रतीक्षा करें ताला जारी करता है, प्रतीक्षा कतार में प्रवेश करता है (एक नाड़ी के लिए इंतजार कर रहा है), और फिर (जब जागृत) लॉक फिर से प्राप्त करता है; पल्स प्रतीक्षा कतार से तैयार कतार तक वस्तुओं की प्रतीक्षा करता है। *** पूरी तरह से *** अलग (अभी तक मानार्थ) उपयोग। पल्स/प्रतीक्षा का उपयोग गर्म या ठंडे लूप की आवश्यकता के बजाय थ्रेड के बीच * समन्वय * करने के लिए किया जाता है। –