Is the C# lock statement FIFO? (first come first serve)

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

If I have the following code:

object a = new object();

void DoSomething()
{
lock(a)
{
Thread.Sleep(5000);
}
}

Say I have 5 threads named a, b, c, d, and e.

If thread a calls this function first, followed in 10ms by threads b, c, d,
and e in that order. Which thread will acquired the lock next? b? WIll
the locks b, c, d, and e acquire the lock in that order EVERY TIME,
regardless of whether it is run on multiple processors, or single
processors, or hyperthreaded processors?

Can someone point me to some documentation that confirms or denies this?

Also, what about Mutex.WaitOne, Monitor.Enter, ManualResetEvent.WaitOne, and
AutoResetEvent.WaitOne?


Thanks,

-Chris
 
Locking is first come first serve, but I wouldn't rely on the order because
any of the factors you mention below (multiple processors, scheduling, etc.)
might affect who the thread lets in and when.

Most if not all of the .NET wrappers behave this way, since they're built on
top of the Win32 locking primitives.
 
No, there is no guarantee about the order in which threads will obtain
ownership of the lock (the underlying critical section).

Willy.
 
Back
Top