Synchronize the Execution of Multiple Threads Using a Semaphore - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Synchronize

Description

Synchronize the Execution of Multiple Threads Using a Semaphore

Demo Code


using System;/*from   w  w  w.  j  a  va 2s  .c  om*/
using System.Threading;

class MainClass
    {
        static bool terminate = false;
        private static void TraceMsg(string msg)
        {
            Console.WriteLine("[{0,3}] - {1} : {2}",Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:mm:ss.ffff"), msg);
        }
        private static void DisplayMessage()
        {
            using (Semaphore sem = Semaphore.OpenExisting("SemaphoreExample"))
            {
                TraceMsg("Thread started.");

                while (!terminate)
                {
                    sem.WaitOne();
                    TraceMsg("Thread owns the Semaphore.");
                    Thread.Sleep(1000);
                    TraceMsg("Thread releasing the Semaphore.");
                    sem.Release();
                    Thread.Sleep(100);
                }
                TraceMsg("Thread terminating.");
            }
        }

        public static void Main()
        {
            using (Semaphore sem = new Semaphore(2,2,"SemaphoreExample"))
            {
                TraceMsg("Starting threads -- press Enter to terminate.");
                Thread trd1 = new Thread(DisplayMessage);
                Thread trd2 = new Thread(DisplayMessage);
                Thread trd3 = new Thread(DisplayMessage);
                trd1.Start();
                trd2.Start();
                trd3.Start();

                terminate = true;
                trd1.Join(5000);
                trd2.Join(5000);
                trd3.Join(5000);
            }
        }
    }

Result


Related Tutorials