Imagine a situation in which there is one king and n is the number of minions presented to him. When the king says “One!”, One of the minions says “Two!”, But only one of them. That is, says only the fastest minion, while others must wait for another king call.
This is my attempt:
using System; using System.Threading; class Program { static bool leaderGO = false; void Leader() { do { lock(this) { //Console.WriteLine("? {0}", leaderGO); if (leaderGO) Monitor.Wait(this); Console.WriteLine("> One!"); Thread.Sleep(200); leaderGO = true; Monitor.Pulse(this); } } while(true); } void Follower (char chant) { do { lock(this) { //Console.WriteLine("! {0}", leaderGO); if (!leaderGO) Monitor.Wait(this); Console.WriteLine("{0} Two!", chant); leaderGO = false; Monitor.Pulse(this); } } while(true); } static void Main() { Console.WriteLine("Go!\n"); Program m = new Program(); Thread king = new Thread(() => m.Leader()); Thread minion1 = new Thread(() => m.Follower('#')); Thread minion2 = new Thread(() => m.Follower('$')); king.Start(); minion1.Start(); minion2.Start(); Console.ReadKey(); king.Abort(); minion1.Abort(); minion2.Abort(); } }
The expected result will be like this (# and $ representing two different minions):
> One!
The order in which they appear does not matter, it would be random. The problem, however, is that this code produces this instead when compiled:
> One!
That is, several minions appear simultaneously. This would cause a storm with even more minions, and the king should not allow such interference.
What will be the possible solution?
For future readers, here is the last working code:
using System; using System.Threading; class Program { static AutoResetEvent leader = new AutoResetEvent(false); static AutoResetEvent follower = new AutoResetEvent(false); void Leader() { do { Console.WriteLine(" One!"); Thread.Sleep(300); follower.Set();
Mutoh source share