生產-消費者模型是多線程編程中的基本模型也是運用最多的模型,而它的原理就是一個線程向緩衝池中扔東西,另一個線程從緩衝池中把東西拿走.所以在這個模型中緩衝池是一個核心,它是生產-消費者之間的橋樑並且能進行一些控制.池滿了則生產者必須等待,池空了則消費者必須等待.這裡的關鍵就是緩衝池必須是固定大小不能隨意擴充,因為程式一瞬間就能把堆耗盡.就是好比我們去蛋糕店買蛋糕,櫃檯和貨架就是緩衝池糕點師是不能無限制的做蛋糕.所以緩衝池的最大,最小值(不一定為0)就是臨界條件.而在我前面的文章中提到了使用Event_Trigger(實際上Event_Trigger就是Semaphore,只不過我自己實現了一個Semaphore)來控制臨界條件,而不是使用雙重檢測這種東西(當然不是說雙重檢測無用,只是應用面很小).我自己實現的鎖Unique中使用了它(但沒有用Event_Trigger來控制臨界條件,在本文中將使用.).我喜歡用Queue來做緩衝池的載體,因為在某些應用中會要求先後順序(FIFO).
public class Info_Queue<_Info>
...{
Queue<_Info> _queue;
Event_Trigger _produce;
Event_Trigger _consume;
Unique _locker = new Unique();
public Info_Queue(int size)
...{
this._queue = new Queue<_Info>(size);
this._produce = new Event_Trigger(size);
this._consume = new Event_Trigger();
}
public void Push(_Info item)
...{
this._produce.Wait();
this._locker.Lock();
this._queue.Enqueue(item);
this._locker.UnLock();
this._consume.Post();
}
public _Info Pop()
...{
this._consume.Wait();
_Info item = default(_Info);
this._locker.Lock();
item = this._queue.Dequeue();
this._locker.UnLock();
this._produce.Post();
return item;
}
public int Count()
...{
return this._queue.Count;
}
public void Clear()
...{
this._queue.Clear();
this._locker.Close();
this._produce.Close();
this._consume.Close();
}
}
下篇文章我將展示如何使用它構造一個對象池.