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