C#線程學習筆記六:線程同步--信號量和互斥體

    本筆記摘抄自:https://www.cnblogs.com/zhili/archive/2012/07/23/Mutex_And_Semaphore.html,記錄一下學習過程以備後續查用。

    一、信號量(Semaphore)

    信號量(Semaphore)是由內核對象維護的int變量。當信號量爲0時,在信號量上等待的線程會堵塞;信號量大於0時,就解除堵塞。當在一個信號量上等待

的線程解除堵塞時,內核自動會將信號量的計數減1。在.NET下通過Semaphore類來實現信號量同步。

    Semaphore類限制可同時訪問某一資源或資源池的線程數。線程通過調用 WaitOne方法將信號量減1,並通過調用Release方法把信號量加1。

    先說下構造函數:

    public Semaphore(int initialCount,int maximumCount);通過兩個參數來設置信號的初始計數和最大計數。

    下面代碼演示信號量同步的使用:

class Program
    {
        //共享資源
        public static int number = 0;
        //初始信號量計數爲0,最大計數爲10。
        public static Semaphore semaphore = new Semaphore(0, 10);
static void Main(string[] args) { #region 線程同步:使用信號量實現同步 for (int i = 0; i < 10; i++) { Thread thread = new Thread(new ParameterizedThreadStart(SemaphoreMethod)); thread.Start(i); } //每次增加2個信號量,即每次釋放2個線程。 for (int j = 0; j < 5; j++) { Console.WriteLine("紅燈轉綠燈……"); semaphore.Release(2); Thread.Sleep(1000); } Console.Read(); #endregion } /// <summary> /// Semaphore方法 /// </summary> public static void SemaphoreMethod(object parameter) { while ((int)parameter != number) { Thread.Sleep(100); } //信號量計數減1 semaphore.WaitOne(); Console.WriteLine("The current value of number is:{0}", ++number); } }

    運行結果如下:

    與上一篇AutoResetEvent類似,信號量也可以實現跨進程間的線程同步。通過調用public Semaphore(int initialCount,int maximumCount,string name);構造函數,

傳入一個信號量名來實現此功能。

    下面代碼演示跨進程間的線程同步:

    第一個進程代碼:

class Program
    {
        //共享資源
        public static int number = 0;
              
        //初始信號量計數爲0,最大計數爲10。
        public static Semaphore semaphore1 = new Semaphore(0, 10, "Semaphore1");
        public static Semaphore semaphore2 = new Semaphore(0, 10, "Semaphore2");

        static void Main(string[] args)
        {
            #region 線程同步:使用信號量實現跨進程之間的線程同步
            for (int i = 0; i < 10; i++)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(Semaphore1Method));
                thread.Start(i);
            }

            //爲了有時間去啓動另外一個進程
            Thread.Sleep(15000);

            //每次增加2個信號量,即每次釋放2個線程。
            for (int j = 0; j < 5; j++)
            {
                Console.WriteLine("信號燈1紅燈轉綠燈……");
                semaphore1.Release(2);
                Console.WriteLine("信號燈2紅燈轉綠燈……");
                semaphore2.Release(2);
                Thread.Sleep(1000);
            }
            Console.Read();
            #endregion
        }

        /// <summary>
        /// Semaphore1方法
        /// </summary>
        public static void Semaphore1Method(object parameter)
        {
            while ((int)parameter != number)
            {
                Thread.Sleep(100);
            }
            //信號量計數減1
            semaphore1.WaitOne();
            Console.WriteLine("Semaphore1:The current value of number is:{0}", ++number);
        }
    }

    第二個進程代碼:

class Program
    {
        //共享資源
        public static int number = 0;
        //創建對象
        public static Semaphore semaphore2 = new Semaphore(0, 10, "Semaphore2");

        static void Main(string[] args)
        {
            #region 通過信號量實現跨進程間的線程同步
            for (int i = 0; i < 10; i++)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(Semaphore2Method));
                thread.Start(i);
            }
            Console.Read();
            #endregion
        }

        /// <summary>
        /// Semaphore2方法
        /// </summary>
        public static void Semaphore2Method(object parameter)
        {
            while ((int)parameter != number)
            {
                Thread.Sleep(100);
            }
            //信號量計數減1
            semaphore2.WaitOne();
            Console.WriteLine("Semaphore2:The current value of number is:{0}", ++number);
        }
    }

    運行結果如下:

    從結果可以看出,第一個進程的semaphore2.Release(2);信號發出後,第二個進程可以收到並釋放線程。

    二、互斥體(Mutex)

    Mutex對象是一個同步基元,當某一個線程佔用Mutex對象時,其他也需要佔用Mutex的線程將處於掛起狀態。

    下面代碼演示互斥體同步的使用:

class Program
    {
        //共享資源
        public static int number = 0;
        //互斥體
        public static Mutex mutex = new Mutex();
        
        static void Main(string[] args)
        {
             #region 線程同步:使用互斥體實現同步
            for (int i = 0; i < 10; i++)
            {
                Thread thread = new Thread(MutexMethod);
                thread.Start();
            }

            Console.Read();
            #endregion
        }

        /// <summary>
        /// Mutex方法
        /// </summary>
        public static void MutexMethod(object parameter)
        {
            mutex.WaitOne();
            Thread.Sleep(500);
            Console.WriteLine("The current value of number is:{0}", ++number);
            mutex.ReleaseMutex();
        }
    }

    運行結果如下:

    下面代碼演示跨進程間的線程同步:

    第一個進程代碼:

class Program
    {
        //共享資源
        public static int number = 0;
  
        //互斥體
        public static Mutex mutex1 = new Mutex(false, "Mutex1");
        public static Mutex mutex2 = new Mutex(false, "Mutex2");

        static void Main(string[] args)
        {
            #region 線程同步:使用互斥體實現跨進程之間的線程同步
            mutex1.WaitOne();
            mutex2.WaitOne();
            for (int i = 0; i < 10; i++)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(Mutex1Method));
                thread.Start(i);
            }

            //爲了有時間去啓動另外一個進程
            Thread.Sleep(15000);
            mutex1.ReleaseMutex();
            mutex2.ReleaseMutex();
            Console.Read();
            #endregion
        }

        /// <summary>
        /// Mutex1方法
        /// </summary>
        public static void Mutex1Method(object parameter)
        {
            mutex1.WaitOne();
            Thread.Sleep(500);
            Console.WriteLine("Mutex1:The current value of number is:{0}", ++number);
            mutex1.ReleaseMutex();
        }
    }

    第二個進程代碼:

class Program
    {
        //共享資源
        public static int number = 0;
        //創建對象
        public static Mutex mutex2 = new Mutex(false, "Mutex2");

        static void Main(string[] args)
        {
            #region 通過互斥體實現跨進程之間的線程同步
            for (int i = 0; i < 10; i++)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(Mutex2Method));
                thread.Start(i);
            }
            Console.Read();
            #endregion
        }

        /// <summary>
        /// Mutex2方法
        /// </summary>
        public static void Mutex2Method(object parameter)
        {
            mutex2.WaitOne();
            Thread.Sleep(500);
            Console.WriteLine("Mutex2:The current value of number is:{0}", ++number);
            mutex2.ReleaseMutex();
        }
    }

    運行結果如下:

    從結果可以看出,第一個進程的mutex2.ReleaseMutex();信號發出後,第二個進程可以收到並釋放線程。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章