How to make the main thread call a random thread and that thread should respond with its number | Sololearn: Learn to code for FREE!
+ 1

How to make the main thread call a random thread and that thread should respond with its number

I have done this question and I am getting correct output but one of the requirement is not fulfilled. 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 it's 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 random condition variable, spurious wakeup should be checked. My solution has every thread simply states it's id with no interaction from the main thread other than waiting for the mutex. But the requirement is that the " Main thread should call a random thread and that thread should respond with its number" How can I achieve that? Any kind of help will be appreciated. https://code.so

4th Jun 2021, 7:35 PM
Jerry Decoder
Jerry Decoder - avatar
2 Réponses
0
Ok, ok, After a long time, and seeing the boring questions , I saw a good question. It is clear that no one knew the answer. I recommend you to use array task Ex: using System; using System.Threading.Tasks; static void StartTasks(int instances) { var tasks = new Task[instances]; for (int i = 0; i < instances; i++) { tasks[i] = new Task((object param) => { var t = (int)param; Console.Write("({0})", t); }, i); } Parallel.ForEach<Task>(tasks, (t) => { t.Start(); }); Task.WaitAll(tasks); }
10th Jun 2021, 4:10 PM
hossein B
hossein B - avatar
0
And for cancelation signal, you must use CancellationToken Ex: static void Main(string[] args) { const int numTasks = 9; CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; Task[] tasks = new Task[numTasks]; for (int i = 0; i < numTasks; i++) tasks[i] = Task.Factory.StartNew(() => PerformTask(token), token); Thread.Sleep(1500); Console.WriteLine("Cancelling tasks"); tokenSource.Cancel(); Console.WriteLine("Cancellation Signalled"); Task.WaitAll(tasks); foreach(Task t in tasks) Console.WriteLine("Tasks {0} state: {1}", t.Id, t.Status); Console.WriteLine("Program End"); Console.ReadLine(); }
10th Jun 2021, 4:13 PM
hossein B
hossein B - avatar