Prizes & Awards
My Profile
Active Members
TodayLast 7 Days
more...
|
New Feature: Community Sites:
Create your own .NET community website and start earning from Google AdSense !
It's Free !
|
Thread Synchronization
Posted Date: 23 Mar 2007 Resource Type: Code Snippets Category: Threading
|
Posted By: Prajnan Das Member Level: Gold Rating: Points: 10
|
The Monitor methods Wait, Pulse and PulseAll go together. They're used to signal between threads. The idea is that one thread calls Wait, which makes it block until another thread calls Pulse or PulseAll. The difference between Pulse and PulseAll is how many threads are woken up: Pulse only wakes up a single waiting thread; PulseAll wakes up all threads waiting on that monitor. In order to call any of these three methods, the thread has to own the monitor of the object reference it passes in as a parameter. When calling Wait, the monitor is released, but then needs to be reacquired before the thread will actually run.
Presented here is an example of resource grabbing competition by two Threads of different priorities. The ResourceAllocator class defines two methods Allocate and Grab. The class uses an internal queue as an storage for integers. The Allocate method en-queues an object into the queue while the Grab method de-queues it. The Grab method waits using Monitor.Wait until there is something to consume from the queue. While the Allocate method calls Monitor.PulseAll to wake up all the threads waiting to consume the integers. The StartCompetition method starts the Allocation in a loop and also spawns two grabber threads of Highest and Lowest Thread priorities.
using System; using System.Collections.Generic; using System.Text; using System.Threading;
namespace ClassLibrary { public class ResourceAllocator { Queue
Here is how you would start the competition:
new ResourceAllocator().StartCompetition();
I had ran this example multiple times and seen that the high priority thread on average acquires 60% of the integers. While if I make priorities equal I can see the difference narrowing and an almost 50% spilt.
|
Responses
|
No responses found. Be the first to respond and make money from revenue sharing program.
|
|