Semaphore.WaitOne /释放VS Monitor.Pulse /等待WaitOne、Semaphore、VS、Pulse

2023-09-03 07:13:47 作者:仄疏

对于我来说现在看起来功能 Semaphore.WaitOne /发布等于 Monitor.Wait /脉冲。跳绳间能力,速度(是的,监视器管理)等非功能性的区别,什么是真正的区别呢?

For me now it looks like functionally Semaphore.WaitOne/Release is equal to Monitor.Wait/Pulse. Skipping interprocess capabilities, speed (yes, Monitor is managed) other nonfunctional differences, what is real difference then?


主要目的旗语是控制访问一组有限的资源。线程可以通过调用的WaitOne 发布参与种源采集。一个THEAD应该叫的WaitOne 来获取资源。然而,将仅在信号灯的计数达到0否则线程可以自由地立即获取阻塞。一旦该线程完成它应该叫发布信号的信号,一个额外的插槽已经被释放了另一个线程。

The main purpose of a Semaphore is to control access to a finite set of resources. Thread can participate in resouce acquisition by calling WaitOne and Release. A thead should call WaitOne to acquire the resource. However, it will only block if the semaphore's count reaches 0 otherwise the thread is free to acquire immediately. Once that thread is finished it should call Release to signal the semaphore that an extra slot has been freed up for another thread.

Monitor.Wait Monitor.Pulse 是截然不同的。首先是没有计算相关。如果脉冲被称为在没有任何呼叫到等待则信号被忽略和抛弃。它不排队以同样的方式,一个信号会。事实上,的行为,等待脉冲本身没有意义了。该等待只是在等待被收购锁的状态的变化(从 Monitor.Enter 收购)。该脉冲的是,事情发生了转变信号。这就是为什么你经常看到等待所谓的,而循环。等待线程必须重新测试等待状态,因为它根本不知道发生了什么变化!

Monitor.Wait and Monitor.Pulse are drastically different. First and foremost there is no counting involved. If Pulse is called in the absence of any call to Wait then the signal is ignored and discarded. It is not queued up in the same way that a semaphore would. In fact, the behavior of Wait and Pulse has no inherent meaning at all. The Wait is simply waiting for a change in the state of the acquired lock (acquired from Monitor.Enter). The Pulse is the signal that something changed. That is why you often see Wait called in a while loop. The waiting thread must retest the wait condition because it has no idea what changed!

Monitor.Wait Monitor.Pulse 是可以用来形成pretty的基本同步机制很多其他的同步设备包括信号量。

Monitor.Wait and Monitor.Pulse are fundamental synchronization mechanisms that can be used to form pretty much any other synchronization device including semaphores.