/* * cv-csharp.csc * * % csc cv-csharp.csc * % ./cv-csharp.exe * * Alternating thread pattern using a Monitor in C#. * * Geoff Voelker * December 2018 */ using System; using System.Threading; public class PingPong { private static String mutex = "lock"; // use a string object as our lock private static int ITERS = 10; public static void Alternate (Object name) { Monitor.Enter (mutex); for (int i = 0; i < ITERS; i++) { Console.WriteLine (name); Thread.Yield (); // 'arbitrary' context switch Monitor.Pulse (mutex); Thread.Yield (); // 'arbitrary' context switch Monitor.Wait (mutex); Thread.Yield (); // 'arbitrary' context switch } // wake up whichever thread is still waiting on the cv Monitor.Pulse (mutex); Monitor.Exit (mutex); } public static void Main () { Thread ping = new Thread (PingPong.Alternate); Thread pong = new Thread (PingPong.Alternate); ping.Start("ping"); pong.Start("pong"); ping.Join(); pong.Join(); } }