Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Question:

Write a program that reads a positive integer value n (n > 3), then creates n threads (each thread has id; id starts from 1) and works until it receives a stop signal. All of n threads are waiting for a signal. Every second main thread sends a signal for a random thread, then that thread should print its id and return to a waiting state.

Requirements:

All additional threads should be finished correctly. At the thread function exit, a message about exit should be printed. While the thread is waiting for the condition variable, spurious wakeup should be checked. Only std::cout allowed for text output. Stop signal is SIGINT (ctrl+c).



Solution :

For my Solution, I am getting the correct output, it’s just that one requirement is not completed. That is - the main difference I see is that the requirements state that the main thread should call a random thread and that thread should respond with its number. Meanwhile, my code has every thread simply states it's id with no interaction from the main thread other than waiting for the mutex.

How can I achieve that?


What I have tried:

C#
class Program //Driver Class
	{


        public static void Main()
        {

            int numberofthreads = Convert.ToInt32(Console.ReadLine());

            ProcessingClass myobject = new ProcessingClass();

            myobject.createThreads(numberofthreads);

            //myobject.ThreadProcess();

        }

        
    }

<pre> public class ProcessingClass
    {
        public Mutex mymutex = new Mutex();
        
        private bool thread_flag = false;
        public void createThreads(int numberofthreads)
        {

            List<Thread> threads = new List<Thread>(numberofthreads);

            for (int i = 0; i < numberofthreads; i++)
            {
                Thread th = new Thread(() =>
                 {
                     threadsworking();

                 });
                
                th.Name = "Thread" + i;
                th.Start(); // <-- .Start() makes the thread start running   
                threads.Add(th);
            }


            //ConsoleKeyInfo consoleKeyInfo = Console.ReadKey();

            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
        {
            var isCtrlC = e.SpecialKey == ConsoleSpecialKey.ControlC;
            //if (consoleKeyInfo.Key == ConsoleKey.C)
                if (isCtrlC)
                {
                thread_flag = true;


                int num = 1;
                foreach (var thread in threads)
                {
                    thread.Join();
                    Console.WriteLine($"Thread {num} exits");
                    num++;
                }
                
            }
            e.Cancel = true;
        };

        }

        public void threadsworking()
        {
            
            while (thread_flag == false)
             {
                

               
                // wait to enter the mutex, give timeout to prevent blocking 
                // until mutex opens and use the bool returned to determine
                // if we should release the mutex or not
                if (mymutex.WaitOne(1))
                {
                    try
                    {
                        Console.WriteLine("{0}", Thread.CurrentThread.Name);
                        Thread.Sleep(1000);    // Wait until it is safe to enter. 
                    }
                    finally
                    {
                        // make sure even if we encounter an error the mutex is released
                        mymutex.ReleaseMutex();    // Release the Mutex.
                    }
                }

                // allow other threads to continue their work instead of blocking with a while loop, this is optional depending on the workload
                Thread.Yield();

            }
            

        }
    }
Posted
Comments
Richard MacCutchan 5-Jun-21 5:13am    
"Only std::cout allowed for text output."

Your instructions suggest this should be written in C++, but you are using C#.
Sneha Shukla09 5-Jun-21 5:39am    
Yes. But I can use C#. And everything is working fine except what I mentioned in the description.
Richard MacCutchan 5-Jun-21 6:03am    
Maybe you should return the List<Thread> object from the call to createThreads. The main method can then get a random number, and use that thread item to get the information.
[no name] 5-Jun-21 13:57pm    
It's a console app; you need a "while" loop in main to do your signal processing every second. If it was a Windows app, you could use a timer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900