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

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
 
K

Klaus H. Probst

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.
 
W

Willy Denoyette [MVP]

No, there is no guarantee about the order in which threads will obtain
ownership of the lock (the underlying critical section).

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top