请您帮我提醒一下最简单的并行编程技术之一。
如何在 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
它不是互斥体,因为没有临界区,或者更确切地说,你可以说有一个无限的临界区。那么它是什么?
最佳答案
关于“如何”...好吧,你可以使用 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)
关于c# - 最简单的并发模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5308900/