We’ve seen how the lock syntax, and how mutexes, can be used for synchronization.
However, using these in their simplest forms is not always sufficient. Consider a situation, where you have a limited number of resources, but greater than 1, with multiple threads trying to access these resources. Assume you have 5 “amounts” of this resource, but 20 threads trying to gain access to one of them. What do you do? You cannot use a single mutex for synchronization, since one mutex can only be owned by one thread at a time, and hence the other 19 threads would be blocked. You could try creating 5 mutex objects, and trying to use code similar to what you saw in Chapter 3, but this too won’t work – since you don’t know which mutexes are currently owned by someone and which aren’t. A mutex object doesn’t expose any property that indicates whether it is owned or not, and if you try calling WaitOne() while the mutex is already owned, the calling thread will be blocked – and so wont have a chance to try some other mutex.
So what do you do? Luckily, there is a way in .NET for you to say something like – “Here – I have 5 mutex objects. Block until any one of them is free, and then let me know which one was free”. Look at the code below:
class Program { static Mutex[] MyMutexes = new Mutex[5]; static void Main(string[] args) { for (int i = 0; i < 5; i++) MyMutexes[i] = new Mutex(); for (int i = 0; i < 20; i++) { Thread T = new Thread(new ThreadStart(ThreadFunc)); T.Start(); } while (true) Thread.Sleep(60000); } public static void ThreadFunc() { while (true) { int index = WaitHandle.WaitAny(MyMutexes); Console.WriteLine("Mutex {0} was free", (index + 1)); Thread.Sleep(1000); MyMutexes[index].ReleaseMutex(); } } }
What we’re doing is, we’ve created 5 mutexes (this corresponds to our 5 “amount” of limited resource that we have). We also create 20 threads, each of which are going to “fight” amongst themselves in order to take ownership of the mutexes. Within the thread functions, we execute
WaitHandle.WaitAny(MyMutexes);
What this does it, it waits for any one of the mutexes in the MyMutexes array to be in an “unowned” state, takes ownership of that mutex, and then returns the index of the mutex of which it obtained ownership. Since there are only 5 mutexes in the array, it implies that at any one time, there will be 15 threads which are blocked on the WaitAny() call.
The line
Thread.Sleep(1000);
corresponds to some work being done by the thread. Once the work is complete, we release the mutex by our familiar ReleaseMutex () call.