Even and Odd number sequence with 2 threads in C# Program

C# multithreading Interview Question: Using two threads print even and odd number in sequence. One thread prints even numbers and another thread prints odd numbers.

Thread T1 : 0,2,4,6…

Thread T2 :1,3,5,7…

Output: 0, 1,2,3,4,5,6,7…

How to create Thread in C# Program?

Answer: To solve this problem let’s use signalling mechanism using  wait () and pulse () method of Monitor class in C#. Other mechanism we can use AutoResetEvent or something.

In below C# program example, we will use wait () method to make the thread waiting and pulse () method to signal other thread.

Use cases:

Even thread will start first to print the number on console.
Even thread will signal odd thread to print the number using pulse() method.
Even thread will wait for signal from odd thread using wait() method.

Same odd thread should do.

Caution:

Since both odd and even threads are sharing console to print the number we need to put a lock over console IO.

Since, we want the sequence should be started with even number, even thread must run first. So, after we will start even thread we need to pause for a moment before starting odd thread using Sleep () method to avoid any chance to start odd thread first or else sequence will be like below

1 0 3 2 5 4 7 6 9 8

Note that for correct sequence even thread must start first.

0 1 2 3 4 5 6 7 8 9 10

C# Program with comments:

using System;
using System.Threading;

namespace odd_even_sequence
{
class Program
{
    // upto the limit numbers will be printed.
    const int numberLimit = 10;

    static object monitor = new object();

    static void Main(string[] args)
    {
        Thread oddThread = new Thread(Odd);
        Thread evenThread = new Thread(Even);


        //Start even thread.
        evenThread.Start();

        //puase for 10 ms, to make sure even thread has started
        //or else odd thread may start first resulting other sequence.
        Thread.Sleep(100);

        //Start odd thread.
        oddThread.Start();

        oddThread.Join();
        evenThread.Join();
        Console.WriteLine("\nPrinting done!!!");
    }

    //printing of Odd numbers
    static void Odd()
    {
        try
        {
            //hold lock as console is shared between threads.
            Monitor.Enter(monitor);
            for (int i = 1; i <= numberLimit; i = i + 2)
            {
                //Complete the task ( printing odd number on console)
                Console.Write(" " + i);
                //Notify other thread that is to eventhread
                //that I'm done you do your job
                Monitor.Pulse(monitor);

                //I will wait here till even thread notify me
                // Monitor.Wait(monitor);

                // without this logic application will wait forever
                bool isLast = i == numberLimit - 1;
                if (!isLast)
                    Monitor.Wait(monitor); //I will wait here till even thread notify me
            }
        }
        finally
        {
            //Release lock
            Monitor.Exit(monitor);
        }
    }

    //printing of even numbers
    static void Even()
    {
        try
        {
            //hold lock
            Monitor.Enter(monitor);
            for (int i = 0; i <= numberLimit; i = i + 2)
            {
                //Complete the task ( printing even number on console)
                Console.Write(" " + i);
                //Notify other thread- here odd thread
                //that I'm done, you do your job
                Monitor.Pulse(monitor);
                //I will wait here till odd thread notify me
                // Monitor.Wait(monitor);

                bool isLast = i == numberLimit;
                if (!isLast)
                    Monitor.Wait(monitor);
            }
        }
        finally
        {
            Monitor.Exit(monitor);//release the lock
        }

    }
}
}

Related Posts