【问题标题】:The simplest concurrency pattern最简单的并发模式
【发布时间】:2011-03-15 07:59:01
【问题描述】:

请你帮我提醒一下最简单的并行编程技术之一。

如何在 C# 中执行以下操作:

初始状态:

semaphore counter = 0

线程 1:

// Block until semaphore is signalled
semaphore.Wait(); // wait until semaphore counter is 1

线程 2:

// Allow thread 1 to run:
semaphore.Signal(); // increments from 0 to 1

它不是互斥体,因为没有临界区,或者你可以说有一个无限临界区。那是什么?

【问题讨论】:

    标签: c# concurrency semaphore parallel-processing


    【解决方案1】:

    关于“如何”...好吧,您可以使用Semaphore、Mutex 或重置事件(ManualResetEvent、AutoResetEvent),但我个人使用Monitor;

    object sync = new object();
    

    线程 1:

    lock(sync) { // blocks until it successfully takes (re-entrant) lock on sync
        // here: launch thread 2, to ensure thread 1 has the lock first
        Monitor.Wait(sync); // releases lock(s) and waits for pulse,
                            // then retakes locks(s) when free
    } // releases lock (or decrement by 1)
    

    线程 2:

    lock(sync) { // blocks until it successfully takes (re-entrant) lock on sync
        Monitor.Pulse(sync); // moves a waiting thread into the ready-queue
                             // (but the awoken thread still can't continue until
                             // it gets the lock itself - and we still hold it)
    } // releases lock (or decrement by 1)
    

    【讨论】:

    • 谢谢!是否需要 lock,因为 Monitor.Pulse 不是原子的?
    • @Ilya - 规则是您只能在持有锁时等待或脉冲。内部?谁知道。但是在不持有锁的情况下尝试任何一个都是即时例外。
    • @Ilya 至于为什么我使用Monitor - 它不涉及操作系统;p(其他都来自操作系统原语)
    【解决方案2】:

    你写的只是一个互斥锁;互斥体基本上与值为 1 的信号量相同。 有一个“临界区”——它是在任一线程持有互斥体时执行的代码序列。

    【讨论】:

      【解决方案3】:

      初始化为 1 的信号量,可以被视为 [read: used] 作为互斥体。 您描述的具体场景是信号量在两个线程之间使用了信号系统。 第一个线程尝试锁定资源 [获取信号量] 但被阻塞 [因为信号量已初始化为零],直到第二个线程向线程 1 发出信号,他可以输入代码的剩余部分。 一篇关于该主题的优秀文章是:

      http://geekswithblogs.net/shahed/archive/2006/06/09/81268.aspx

      【讨论】:

      • 谢谢!实际上这是我的第一个解决方案,但后来我将其更改为 Marc 的答案,因为它看起来更整洁。
      猜你喜欢
      • 2016-07-04
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多