views:

57

answers:

1

When AutoResetEvent calls WaitOne on Process 1 and it is called again in Process2, and Process 2 calls Set on the same AutoResetEvent, shouldn't it release the lock on Process1 as it was called before the one in Process 2?

I have a sample code which I used to execute Process 1 and 2. I run Process 1 without any arguments, so it hangs at wh.WaitOne(). I run Process 2 with an argument, so that it calls Set() What I observed is that Process 2's lock is released instead of Process1's.

Should AutoResetEvent's lock queue behave as first in first out?

class ThreadSafe
{
    static EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset, "abc");

    static void Waiter(String t)
    {
            wh.WaitOne();
    }

    static void Main(string[] args)
    {
        new Thread(delegate() { Waiter("a"); }).Start();

        if (args.Length > 0)
        {
            wh.Set();
        }
    }
}
+1  A: 

'Fairness' in locking is being deprecated, I could only find this link but I remember reading some more recent/relevant articles. If I recall correctly, all locking mechanisms in .NET are giving up FIFO behaviour.

The morale: you should not rely on FIFO order. Multi-threading is harder than it looks.

Henk Holterman