I am spawning 10 threads using a for loop in C# as shown below
internal class Program
{
static Mutex mutex = new Mutex();
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Thread t1 = new Thread(AcquireMutex);
t1.Name = string.Format("Thread{0}", i + 1);
t1.Start();
}
}
private static void AcquireMutex(object? obj)
{
mutex.WaitOne();
DoSomething();
mutex.ReleaseMutex();
Console.WriteLine("Mutex released by {0}", Thread.CurrentThread.Name);
}
private static void DoSomething()
{
Thread.Sleep(1000);
Console.WriteLine("Mutex acquired by {0}", Thread.CurrentThread.Name);
}
}
As per my understanding, in the first iteration of the for loop Thread 1 starts and so on. But while running the above code,I came to see that Thread 10 acquires the mutex lock before Thread 1 in some cases.
So my query is , if the for loop spawns Thread 1 first ,then Thread 10, why does Thread 10 acquires the lock first in some cases?