0
在我的計算機科學課,我們有幾個不同的信號量實現。信號量實現:監控與睡眠理髮,巨大的性能差異
監督執行:
class Semaphore {
int s; object mutex = new object();
public Semaphore(int n) { s = n; }
public void P()
{
lock (mutex)
{
while (s == 0) Monitor.Wait(mutex);
s--;
}
}
public void V()
{
lock (mutex)
{
s++; Monitor.Pulse(mutex);
}
}
}
睡覺理髮Implentation:其中兩個是由使用普通顯示器的實現和一個使用睡眠理髮實施完成
class Semaphore {
int s; object mutex = new object();
public Semaphore (int n) { s = n; }
public void P()
{
lock(mutex)
{
s--;
if (s < 0) Monitor.Wait(mutex);
}
}
public void V()
{
lock(mutex)
{
s++;
if (s <= 0) Monitor.Pulse(mutex);
}
}
}
兩個實施似乎非常相似,我。我看到的唯一區別是,s在睡眠理髮師實現和Monitor實現中變爲負數,直到執行V()時,它停留在s = 0。
但測量有一個巨大的差異(數據來自演示幻燈片):
Semaphore Type Time (ms)
Monitor 7549
Monitor (Barber) 109598
什麼是對那些巨大的不同性能比較結果的可能的解釋?
s通常從哪裏開始?如果s從0開始,則在V() –
@ Me.Name的第二個實現中從不會調用Pulse:s是從0開始的示例:s.P()等待並且s = -1。然後s.V(),所以s變爲0並且調用Pulse。我不知道你的意思是什麼,這是行不通的。你能說出你的意思嗎? – anopows