semaphore
semaphore
什麼是信號量(Semaphore0
Semaphore分爲單值和多值兩種,前者只能被一個線程獲得,後者可以被若干個線程獲得。
以一個停車場是運作爲例。爲了簡單起見,假設停車場只有三個車位,一開始三個車位都是空的。這是如果同時來了五輛車,看門人允許其中三輛不受阻礙的進入,然後放下車攔,剩下的車則必須在入口等待,此後來的車也都不得不在入口處等待。這時,有一輛車離開停車場,看門人得知後,打開車攔,放入一輛,如果又離開兩輛,則又可以放入兩輛,如此往復。
在這個停車場系統中,車位是公共資源,每輛車好比一個線程,看門人起的就是信號量的作用。
更進一步,信號量的特性如下:信號量是一個非負整數(車位數),所有通過它的線程(車輛)都會將該整數減一(通過它當然是爲了使用資源),當該整數值爲零時,所有試圖通過它的線程都將處於等待狀態。在信號量上我們定義兩種操作: Wait(等待)和 Release(釋放)。當一個線程調用Wait等待)操作時,它要麼通過然後將信號量減一,要麼一自等下去,直到信號量大於一或超時。Release(釋放)實際上是在信號量上執行加操作,對應於車輛離開停車場,該操作之所以叫做“釋放”是應爲加操作實際上是釋放了由信號量守護的資源。
實現
大家都知道,.Net Framework類庫中提供的線程同步設施包括:
Monitor, AutoResetEvent, ManualResetEvent,Mutex,ReadWriteLock和 InterLock。其中 AutoResetEvent, ManualResetEvent,Mutex派生自WaitHandler,它們實際上是封裝了操作系統提供的內核對象。而其它的應當是在.Net虛擬機中土生土長的。顯然來自操作系統內核對象的設施使用起來效率要差一些。不過效率並不是我們這裏要考慮的問題,我們將使用兩個 Monitor 和一個ManualResetEvent 對象來模擬一個信號量。
代碼如下:
public class Semaphore
{
private ManualResetEvent waitEvent = new ManualResetEvent(false);
private object syncObjWait = new object();
private int maxCount = 1; file://最大資源數
private int currentCount = 0; file://當前資源數
public Semaphore()
{
}
public Semaphore( int maxCount )
{
this.maxCount = maxCount;
}
public bool Wait()
{
lock( syncObjWait ) file://只能一個線程進入下面代碼
{
bool waitResult = this.waitEvent.WaitOne(); file://在此等待資源數大於零
if( waitResult )
{
lock( this )
{
if( currentCount > 0 )
{
currentCount--;
if( currentCount == 0 )
{
this.waitEvent.Reset();
}
}
else
{
System.Diagnostics.Debug.Assert( false, "Semaphore is not allow current count < 0" );
}
}
}
return waitResult;
}
}
/**//// <summary>
/// 允許超時返回的 Wait 操作
/// </summary>
/// <param name="millisecondsTimeout"></param>
/// <returns></returns>
public bool Wait( int millisecondsTimeout )
{
lock( syncObjWait ) // Monitor 確保該範圍類代碼在臨界區內
{
bool waitResult = this.waitEvent.WaitOne(millisecondsTimeout,false);
if( waitResult )
{
lock( this )
{
if( currentCount > 0 )
{
currentCount--;
if( currentCount == 0 )
{
this.waitEvent.Reset();
}
}
else
{
System.Diagnostics.Debug.Assert( false, "Semaphore is not allow current count < 0" );
}
}
}
return waitResult;
}
}
public bool Release()
{
lock( this ) // Monitor 確保該範圍類代碼在臨界區內
{
currentCount++;
if( currentCount > this.maxCount )
{
currentCount = this.maxCount;
return false;
}
this.waitEvent.Set(); file://允許調用Wait的線程進入
}
return true;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.