Monday, August 10, 2009

FIFO, fairness and synchronization primitives

Recently I ran a few multithreaded tests to figure out whether FIFO principle (First In, First Out) is respected for ManualResetEvent, AutoResetEvent, ReaderWriterLockSlim or the Monitor. I'm glad to report: all those nice things mentioned above do not support FIFO.

Why bother with FIFO in the first place? Well, it's a question of fairness: say you have a ReaderWriterLockSlim (or any other primitive from the list above) along with 2 writers waiting for a lock, one of them has been waiting for a minute and a half, and the other one has been waiting for only 2 seconds -- are they really equal like ReaderWriterLockSlim assumes, or are they not? I think, in the scenario described, we should favor the writer that started waiting earlier. You can use queues to achieve just that (at least this is what I did). This applies to any synchronization primitive.

Monitor seems to be the nicest of all four: it behaves perfectly well in terms of FIFO on a single-CPU, single-core PC. However, this is not the case with Quad-core processors, for instance.