信號量 Semaphore
類似互斥鎖,但它可以允許多個線程同時訪問一個共享資源
通過使用一個計數器來控制對共享資源的訪問,如果計數器大於0,就允許訪問,如果等於0,就拒絕訪問。計數器累計的是“許可證”的數目,為了訪問某個資源。線程必須從信號量獲取一個許可證。
通常在使用信號量時,希望訪問共享資源的線程將嘗試獲取一個許可證,如果信號量的計數器大於0,線程將獲取一個許可證並將信號量的計數器減1,否則先線程將阻塞,直到獲取一個許可證;當線程不再需要共享資源時,將釋放鎖擁有的許可證,並將許可證的數量加1,如果有其他的線程正在等待許可證,那么該線程將立刻獲取許可證。
另外,允許同時訪問的資源的進程數量是在創建信號量時指定的,如果創建一個允許進程訪問的信號量數目為1,則該信號量就和互斥鎖的用法一樣。
Public Semaphore(int initialCount,int maximumCount)
initialCount指信號量許可證的初始值,maximumCount為最大值
獲取許可證使用WaitOne()
不需要時釋放使用 public int Release();或者public int Release(int releaseCount);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MyTTCon
{
class mythread
{
public Thread thrd;
//創建一個可授權2個許可證的信號量,且初始值為2
static Semaphore sem = new Semaphore(2, 2);
public mythread(string name)
{
thrd = new Thread(this.run);
thrd.Name = name;
thrd.Start();
}
void run()
{
Console.WriteLine(thrd.Name + "正在等待一個許可證……");
//申請一個許可證
sem.WaitOne();
Console.WriteLine(thrd.Name + "申請到許可證……");
for (int i = 0; i < 4 ; i++)
{
Console.WriteLine(thrd.Name + ": " + i);
Thread.Sleep(1000);
}
Console.WriteLine(thrd.Name + " 釋放許可證……");
//釋放
sem.Release();
}
}
class mysemaphore
{
public static void Main()
{
mythread mythrd1 = new mythread("Thrd #1");
mythread mythrd2 = new mythread("Thrd #2");
mythread mythrd3 = new mythread("Thrd #3");
mythread mythrd4 = new mythread("Thrd #4");
mythrd1.thrd.Join();
mythrd2.thrd.Join();
mythrd3.thrd.Join();
mythrd4.thrd.Join();
}
}
}
