C# Alternating threads

Posted by Mutoh on Stack Overflow See other posts from Stack Overflow or by Mutoh
Published on 2012-11-20T22:18:18Z Indexed on 2012/11/20 23:01 UTC
Read the original article Hit count: 173

Filed under:
|

Imagine a situation in which there are one king and n number of minions submissed to him. When the king says "One!", one of the minions says "Two!", but only one of them. That is, only the fastest minion speaks while the others must wait for another call of the king.

This is my try:

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 output would be this (# and $ representing the two different minions):

> One!
# Two!
> One!
$ Two!
> One!
$ Two!

...

The order in which they'd appear doesn't matter, it'd be random. The problem, however, is that this code, when compiled, produces this instead:

> One!
# Two!
$ Two!
> One!
# Two!
> One!
$ Two!
# Two!

...

That is, more than one minion speaks at the same time. This would cause quite the tumult with even more minions, and a king shoudln't allow a meddling of this kind.

What would be a possible solution?

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading