【问题标题】:Semaphore Implementation: Monitor vs. Sleeping Barber, huge performance difference信号量实现:Monitor vs. Sleeping Barber,巨大的性能差异
【发布时间】:2012-07-02 09:29:35
【问题描述】:

在我的计算机科学课上,我们有几个不同的信号量实现。其中两个是使用普通的 Monitor 实现完成的,一个是使用 Sleeping Barber 实现的:

监控实现:

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); 
        }
}

}

睡觉理发器植入:

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 在 sleep barber 实现中变为负数,而在 Monitor 实现中它保持在 s=0 直到 V() 被执行。

但测量结果存在巨大差异(来自演示幻灯片的数据):

Semaphore Type     Time (ms)
Monitor                 7549
Monitor (Barber)      109598

对于这些巨大的不同性能结果有什么可能的解释?

【问题讨论】:

  • s 通常从哪里开始?如果 s 从 0 开始,则在 V() 的第二个实现中永远不会调用 Pulse
  • @Me.Name:如果 s 从 0 开始的示例:s.P() 等待并且 s=-1。然后 s.V(),因此 s 变为 0 并调用 Pulse。我不知道你的意思是什么例子不起作用。你能说清楚你的意思吗?

标签: c# performance locking semaphore monitor


【解决方案1】:

我很确定这是因为第一个解决方案中的while,而第二个解决方案只使用ifwhile 会反复检查条件,导致等待直到某个时间片出现。

【讨论】:

    猜你喜欢
    • 2015-01-13
    • 2019-04-21
    • 2010-10-15
    • 2013-02-18
    • 2016-08-19
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多