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?
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(); } } }
List<Thread>
createThreads
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)