C#中的訊號量


訊號量類允許您設定對臨界區有訪問許可權的執行緒數的限制。此類用於控制對資源池的訪問。System.Threading.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+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告