拜托,请您帮我想起最简单的并行编程技术之一。

如何在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


它不是互斥锁,因为没有临界区,或者您可以说存在无限的临界区。那是什么

最佳答案

关于“如何”……好吧,您可以使用SemaphoreMutex或重置事件(ManualResetEventAutoResetEvent),但是我个人使用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)

关于c# - 最简单的并发模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5308900/

10-11 14:26