I require a section of the code to be run by only one thread at time (single resource lock).
the lock(object)
statement in C# allows this. It doesn't however, preserve the order of requests to the lock.
For example, consider the 100 threadstarts below where numbered threads try to lock on padlock in order:
for (int i = 0; i < 100; i++)
{
(new Thread(delegate(object index)
{
int name = (int) index;
byte[] len = new byte[2];
Console.WriteLine(string.Format("Thread:{0} going for lock. ",
name));
lock (padlock)
{
rnd.GetBytes(len);
ushort l = BitConverter.ToUInt16(len, 0);
Console.WriteLine(string.Format("Thread:{0} sleeping: {1}",
name, l));
Thread.Sleep(l);
}
})).Start(i);
The actual granting of the access is not in perfect order (1->100) or NOT FIFO. However there does seem to be an "early-in-early-out" EIEO pattern (run by a heap perhaps?).
The Question is: What determines the lock granting order and can it be relied on not starving an unlucky thread?
Update: this answer explains it. Here is the pertinent quote (Joe Duffy's Concurrent Programming on Windows):
Because monitors use kernel objects internally, they exhibit the same roughly-FIFO behavior that the OS synchronization mechanisms also exhibit (described in the previous chapter). Monitors are unfair, so if another thread tries to acquire the lock before an awakened waiting thread tries to acquire the lock, the sneaky thread is permitted to acquire a lock.