C#中的訊號量


Semaphore 類允許您設定對臨界區有訪問許可權的執行緒數量的限制。該類用於控制對資源池的訪問。System.Threading.Semaphore 是 Semaphore 的名稱空間,因為它包含實現 Semaphore 所需的所有方法和屬性。

要在 C# 中使用訊號量,您只需要例項化 Semaphore 物件的一個例項即可。它至少有兩個引數:

參考

MSDN

序號建構函式和描述
1Semaphore(Int32,Int32)
初始化 Semaphore 類的新的例項,指定初始條目數和最大併發條目數。
2Semaphore(Int32,Int32,String) −
初始化 Semaphore 類的新的例項,指定初始條目數和最大併發條目數,並可選地指定系統訊號量物件的名稱。
3Semaphore(Int32,Int32,String,Boolean)
初始化 Semaphore 類的新的例項,指定初始條目數和最大併發條目數,可選地指定系統訊號量物件的名稱,並指定一個變數,該變數接收一個值,指示是否建立了一個新的系統訊號量。

現在讓我們看一個例子

在這裡,我們使用了以下 Semaphore 建構函式,它初始化 Semaphore 類的新的例項,指定最大併發條目數,並可選地預留一些條目。

static Semaphore semaphore = new Semaphore(2, 2);

示例

即時演示

using System;
using System.Threading;
namespace Program
{
class Demo
   {
      static Thread[] t = new Thread[5];
      static Semaphore semaphore = new Semaphore(2, 2);
      static void DoSomething()
      {
         Console.WriteLine("{0} = waiting", Thread.CurrentThread.Name);
         semaphore.WaitOne();
         Console.WriteLine("{0} begins!", Thread.CurrentThread.Name);
         Thread.Sleep(1000);
         Console.WriteLine("{0} releasing...", Thread.CurrentThread.Name);
         semaphore.Release();
      }
      static void Main(string[] args)
      {
         for (int j = 0; j < 5; j++)
         {
            t[j] = new Thread(DoSomething);
            t[j].Name = "thread number " + j;
            t[j].Start();
         }
         Console.Read();
      }
   }
}

輸出

以下是輸出結果

thread number 2 = waiting
thread number 0 = waiting
thread number 3 = waiting
thread number 1 = waiting
thread number 4 = waiting
thread number 2 begins!
thread number 1 begins!
thread number 2 releasing...
thread number 1 releasing...
thread number 4 begins!
thread number 3 begins!
thread number 4 releasing...
thread number 0 begins!
thread number 3 releasing...
thread number 0 releasing...

更新於: 2020年4月1日

3K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告