in

Monitor.Pulse(All) then Monitor.Wait()


Today I’ve seen a PulseAll()/Wait() combo like in the code below for the first time.

The code below is a simplified version I just used to verify if the 2 threads would actually run in an alternating fashion (the real code I saw this had the PulseAll/Wait combo in a producer thread and a consumer thread, and there are conditions so that it all makes more sense). And they do always run alternately!

My question: Is this common practice, in cases where 2 threads want to wake up each other alternately? (Well, aside from the fact that Pulse() would probably do as well here)

int flipflop = 0;
object q = new object();
new Thread(() =>
{
    while (true)
    {
        lock(q)
        {
            if (Interlocked.CompareExchange(ref flipflop, 1, 0) != 0)
                throw new Exception("flip");
            Monitor.PulseAll(q);
            Monitor.Wait(q);
        }
    }
}).Start();
Thread.Sleep(1000); // just to make sure above thread starts before below one
new Thread(() =>
{
    while (true)
    {
        lock (q)
        {
            if (Interlocked.CompareExchange(ref flipflop, 0, 1) != 1)
                throw new Exception("flop");
            Monitor.PulseAll(q);
            Monitor.Wait(q);
        }
    }
}).Start();
while (true)
{
    Console.WriteLine(DateTime.Now.TimeOfDay + ": " + Volatile.Read(ref flipflop));
    Thread.Sleep(1000);
}



Source: https://stackoverflow.com/questions/70721917/monitor-pulseall-then-monitor-wait

Instagram Account Reporting Tool

CAD Designs of iPhone SE 3 Leaked Online, Launch Expected in April 2022