5

I was wondering on the Monitor Class. As far as i know all waiting threads are not FIFO. The first one that aquires the lock is not allways the first on in the waiting queue. Is this correct? Is there some way to ensure the FIFO condition?

Regards

Tudor
  • 61,523
  • 12
  • 102
  • 142
Mantzas
  • 2,463
  • 3
  • 25
  • 35
  • Good question. Have you read this? http://stackoverflow.com/questions/5111779/lock-monitor-internal-implementation-in-net – Jeb Feb 14 '12 at 14:16
  • Why does fifo matter? Since you can't really guarantee the order in which the threads will arrive. Also with asynchronous call procedures (APC) you can't even guarantee a waiting thread won't be borrowed for a moment to service a callback before returning to wait on the lock. – Chris Chilvers Feb 14 '12 at 14:16
  • @ChrisChilvers FIFO can matter a lot! So much so that Microsoft have now introduced locks which guarantee FIFO behaviour. – adelphus Feb 14 '12 at 14:21
  • @adelphus I agree. Can you point me which locks guarantee FIFO behavior?? – Mantzas Feb 14 '12 at 14:28
  • Not in .NET I'm afraid. The locks I was talking about are in kernel-mode: http://msdn.microsoft.com/en-us/library/windows/hardware/ff559970(v=vs.85).aspx – adelphus Feb 14 '12 at 14:51

3 Answers3

3

If you are referring to a built-in way, then no. Repeatedly calling TryEnter in a loop is by definition not fair and unfortunately neither is the simple Monitor.Enter. Technically a thread could wait forever without getting the lock.

If you want absolute fairness you will need to implement it yourself using a queue to keep track of arrival order.

Tudor
  • 61,523
  • 12
  • 102
  • 142
3

Is there some way to ensure the FIFO condition?

In a word: no!

I wrote a short article about this: Is the Ready Queue FIFO?

Nick Butler
  • 24,045
  • 4
  • 49
  • 70
2

Look at this question, I think it will very useful for you - Does lock() guarantee acquired in order requested?

especially this quote:

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.

Community
  • 1
  • 1
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161