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

CSharp examples for Thread Asynchronous:Synchronize

Description

Synchronize the Execution of Multiple Threads Using a Mutex

Demo Code


using System;//  w w  w. j a  v a  2s . c o  m
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 (Mutex mutex = new Mutex(false, "MutexExample"))
            {
                TraceMsg("Thread started.");

                while (!terminate)
                {
                    mutex.WaitOne();
                    TraceMsg("Thread owns the Mutex.");
                    Thread.Sleep(1000);
                    TraceMsg("Thread releasing the Mutex.");
                    mutex.ReleaseMutex();
                    Thread.Sleep(100);
                }
                TraceMsg("Thread terminating.");
            }
        }

        public static void Main()
        {
            using (Mutex mutex = new Mutex(false, "MutexExample"))
            {
                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