educative.io

Incorrect output on last sample

The last sample of this page is give incorrect output for prime numbers

Hello @Kumar_Abhishek_Verma

Thanks for letting us know, we will update this issue soon. For the time being, I am attaching the complete, correct code. Please use this code to understand the concept.

using System;
using System.Threading;

class Demonstration
{
    static void Main()
    {
        new PrimeFinderMonitor().run();
    }
}

public class PrimeFinderMonitor
{
    bool found = false;
    int prime;
    volatile bool shutdown = false;
    Object lockObj = new Object();

    private bool isPrime(int i)
    {
        if (i == 2 || i == 3) return true;

        int div = 2;

        while (div <= i / 2)
        {
            if (i % div == 0) return false;
            div++;
        }

        return true;
    }


    public void printer()
    {
        while (!shutdown)
        {
            Monitor.Enter(lockObj);

            while (!found && !shutdown)
            {
                Monitor.Wait(lockObj);
            }

            Console.WriteLine("Prime found to be = " + prime);

            found = false;
            Monitor.PulseAll(lockObj);
            Monitor.Exit(lockObj);
        }

        // Wake up any blocked finder threads
        // Monitor.Enter(lockObj);
        // Monitor.PulseAll(lockObj);
        // Monitor.Exit(lockObj);
    }


    public void finder()
    {
        while (!shutdown)
        {
            Monitor.Enter(lockObj);


            if (isPrime(prime))
            {
                found = true;
                Monitor.PulseAll(lockObj);
            }
            
            while (found && !shutdown)
            {
                Monitor.Wait(lockObj);
            }

            prime++;
            Monitor.Exit(lockObj);
        }

        // Wake up any finder threads
        // Monitor.Enter(lockObj);
        // Monitor.PulseAll(lockObj);
        // Monitor.Exit(lockObj);
    }


    public void run()
    {

        Thread primeFinderThread = new Thread(new ThreadStart(finder));
        Thread primeFinderThread2 = new Thread(new ThreadStart(finder));
        Thread primeFinderThread3 = new Thread(new ThreadStart(finder));
        Thread printerThread = new Thread(new ThreadStart(printer));

        primeFinderThread.Start();
        primeFinderThread2.Start();
        primeFinderThread3.Start();
        printerThread.Start();


        Thread.Sleep(1000);

        shutdown = true;

        printerThread.Join();
        primeFinderThread2.Join();
        primeFinderThread3.Join();
        primeFinderThread.Join();
    }
}

I hope this will help you; please let me know if you still have any confusion.

Thank You :blush: