CATEGORII DOCUMENTE |
Asp | Autocad | C | Dot net | Excel | Fox pro | Html | Java |
Linux | Mathcad | Photoshop | Php | Sql | Visual studio | Windows | Xml |
The Wait() and Pulse() mechanism is used for interaction between threads. When a Wait() method is issued on an object, the thread that is accessing that object waits until it gets a signal to wake up. The Pulse() and PulseAll() are used for signaling to waiting thread(s). The following listing is an example of how the Wait() and Pulse() methods work, WaitAndPulse.cs:
The Wait() and Pulse() methods can be called only within the Enter() and Exit() code block.
using System;The output from WaitAndPulse is:
WaitPulse1:Entered Thread 2In
the
Assuming that WaitPulse1.CriticalSection() gets called first, then thread t1 enters the critical section of the method with a lock on the LockMe object and then executes Monitor.Wait() in the for loop. By executing Monitor.Wait(), it is waiting for a runtime notification (Monitor.Pulse()) from another thread to be woken up. We lock the LockMe object because we want only one thread to access the shared LockMe instance at any point of time.
Note that when the thread executes the Monitor.Wait() method, it releases the lock on the LockMe object temporarily, so that other threads can access it. After thread t1 goes into the waiting state, thread t2 is free to access the LockMe object. Even though the LockMe object is a separate object (WaitPulse1 and WaitPulse2), they both refer to the same object reference. Thread t2 acquires the lock on the LockMe object and enters the WaitPulse2.CriticalSection() method. As soon as it enters the for loop, it sends a run-time notification (Monitor.Pulse()) to the thread that is waiting on the LockMe object (t1 in this case) and goes off to the waiting state. As a result, t1 wakes up and acquires the lock on the LockMe object. Thread t1 then accesses the result variable and sends a run-time notification to the thread waiting on the LockMe object (thread t2 in this case). This cycle continues until the for loop ends.
If you compare the description above with the output of the program, the concept will be crystal clear. It is important to note that every Enter() method should be accompanied by an Exit() method or else the program will never quit.
The Enter() method takes an object as a parameter. If the object parameter is null, a method variable, or an object of a value type like an integer an exception will be thrown.
Politica de confidentialitate | Termeni si conditii de utilizare |
Vizualizari: 815
Importanta:
Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved