Click here to Skip to main content
15,881,882 members
Articles / General Programming / Threads

Thread Synchronization with Semaphore

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
19 Nov 2011CPOL1 min read 54.9K   1.6K   31  
An introduction to semaphore in contrast to Monitor
using System;
using System.Windows.Forms;
using System.Threading;
namespace SemaphoreApp
{
    public partial class SemaphoreManager : Form
    {
        public SemaphoreManager()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Description : No Synchronization
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNoSync_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("== No Synchronization ===========");
            int TotalThread = 5;
            Thread[] Threads = new Thread[TotalThread];
            for (int i = 0; i < TotalThread; i++)
            {
                Threads[i] = new Thread(new ThreadStart(AccessCode));
                Threads[i].IsBackground = true;
                Threads[i].Start();
            } 
        }
        /// <summary>
        /// Description : Synchronization with Minitor
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonMonitor_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("== Using Monitor =============");
            int TotalThread = 5;
            Thread[] Threads = new Thread[TotalThread];
            for (int i = 0; i < TotalThread; i++)
            {
                Threads[i] = new Thread(new ThreadStart(AccessCodeWithMonitor));
                Threads[i].IsBackground = true;
                Threads[i].Start();
            }
        }
        /// <summary>
        /// Description : Synchronization with semaphore
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSemaphore_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("== Using Semaphore =============");
            int TotalThread = 5;
            int SemaphoreCount = 3;
            Thread[] Threads = new Thread[TotalThread];
            Semaphore Sema = new Semaphore(SemaphoreCount, SemaphoreCount);

            for (int i = 0; i < TotalThread; i++)
            {
                Threads[i] = new Thread(new ParameterizedThreadStart(AccessCodewithSemaphore));
                Threads[i].IsBackground = true;
                Threads[i].Start(Sema);
            }
        }
        /// <summary>
        /// Description : Access Code with No Synchronization
        /// </summary>
        public void AccessCode()
        {
            listBox1.BeginInvoke(new ParameterizedThreadStart(UpdateUI), new object[] { "Thread ID : " + Thread.CurrentThread.ManagedThreadId.ToString() + " : Entered" });
            Thread.Sleep(500);
            listBox1.BeginInvoke(new ParameterizedThreadStart(UpdateUI), new object[] { "Thread ID : " + Thread.CurrentThread.ManagedThreadId.ToString() + " : Exit" });
        }
        /// <summary>
        /// Description : Access Code with Semaphore
        /// </summary>
        public void AccessCodeWithMonitor()
        {
            Monitor.Enter(this);
            try
            {
                listBox1.BeginInvoke(new ParameterizedThreadStart(UpdateUI), new object[] { "Thread ID : " + Thread.CurrentThread.ManagedThreadId.ToString() + " : Entered" });
                Thread.Sleep(500);
                listBox1.BeginInvoke(new ParameterizedThreadStart(UpdateUI), new object[] { "Thread ID : " + Thread.CurrentThread.ManagedThreadId.ToString() + " : Exit" });
            }
            finally
            {
                Monitor.Exit(this);
            }
        }
        /// <summary>
        /// Description : Access Code with Semaphore
        /// </summary>
        /// <param name="S"></param>
        public void AccessCodewithSemaphore(object objSemaphore)
        {
            bool IsComplete = false;
            Semaphore l_SemaPhore = (Semaphore)objSemaphore;
            while (!IsComplete)
            {
                if (l_SemaPhore.WaitOne(200, false))
                {
                    try
                    {
                        listBox1.BeginInvoke(new ParameterizedThreadStart(UpdateUI), new object[] { "Thread ID : " + Thread.CurrentThread.ManagedThreadId.ToString() + " : Entered" });
                        Thread.Sleep(500);
                    }
                    finally
                    {
                        l_SemaPhore.Release();
                        listBox1.BeginInvoke(new ParameterizedThreadStart(UpdateUI), new object[] { "Thread ID : " + Thread.CurrentThread.ManagedThreadId.ToString() + " : Exit" });
                        IsComplete = true;
                    }
                }
                else
                {
                    listBox1.BeginInvoke(new ParameterizedThreadStart(UpdateUI), new object[] { "Thread ID : " + Thread.CurrentThread.ManagedThreadId.ToString() + " : Waiting To enter" });
                }
            }
        }
        /// <summary>
        /// Description : Used To Update UI
        /// </summary>
        /// <param name="s"></param>
        public void UpdateUI(object s)
        {
            listBox1.Items.Add(s.ToString());
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Sapient Corporation Pvt. Ltd.
India India
Software Devloper sience 2006. Experience on VB 6.0,C# Web, Windows and Distributed application like WCF etc. Currently working at Sapient Corporation Pvt. Ltd

Comments and Discussions