Does lock() guarantee acquired in order requested?

IIRC, it’s highly likely to be in that order, but it’s not guaranteed. I believe there are at least theoretically cases where a thread will be woken spuriously, note that it still doesn’t have the lock, and go to the back of the queue. It’s possible that’s only for Wait/Notify, but I have a sneaking suspicion it’s for locking as well.

I definitely wouldn’t rely on it – if you need things to occur in a sequence, build up a Queue<T> or something similar.

EDIT: I’ve just found this within Joe Duffy’s Concurrent Programming on Windows which basically agrees:

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.

The “roughly-FIFO” bit is what I was thinking of before, and the “sneaky thread” bit is further evidence that you shouldn’t make assumptions about FIFO ordering.

Leave a Comment