Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread signaling basics

In C# how does one achieve thread signaling?

like image 210
Marcote Avatar asked Apr 23 '10 03:04

Marcote


People also ask

How do you signal between threads?

The common ways of signalling are through WaitHandle and Monitor , that can coordinate between threads by notifying (signal) them when to go ahead and when to halt. All the EventWaitHandle mentioned below are basically WaitHandle objects that can signal and wait for signals.

How do you stop a thread from signaling?

To stop a worker thread call workerThread. interrupt() this will cause certain methods (like Thread. sleep()) to throw an interrupted exception. If your threads don't call interruptable methods then you need to check the interrupted status.

Are signals shared between threads?

Signal management in multithreaded processes is shared by the process and thread levels, and consists of the following: Per-process signal handlers. Per-thread signal masks. Single delivery of each signal.


1 Answers

Here is a custom-made console application example for you. Not really a good real world scenario, but the usage of thread signaling is there.

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        bool isCompleted = false;
        int diceRollResult = 0;

        // AutoResetEvent is one type of the WaitHandle that you can use for signaling purpose.
        AutoResetEvent waitHandle = new AutoResetEvent(false);

        Thread thread = new Thread(delegate() {
            Random random = new Random();
            int numberOfTimesToLoop = random.Next(1, 10);

            for (int i = 0; i < numberOfTimesToLoop - 1; i++) {
                diceRollResult = random.Next(1, 6);

                // Signal the waiting thread so that it knows the result is ready.
                waitHandle.Set();

                // Sleep so that the waiting thread have enough time to get the result properly - no race condition.
                Thread.Sleep(1000);
            }

            diceRollResult = random.Next(1, 6);
            isCompleted = true;

            // Signal the waiting thread so that it knows the result is ready.
            waitHandle.Set();
        });

        thread.Start();

        while (!isCompleted) {
            // Wait for signal from the dice rolling thread.
            waitHandle.WaitOne();
            Console.WriteLine("Dice roll result: {0}", diceRollResult);
        }

        Console.Write("Dice roll completed. Press any key to quit...");
        Console.ReadKey(true);
    }
}
like image 89
Amry Avatar answered Sep 18 '22 14:09

Amry