Semaphore.WaitOne /释放VS Monitor.Pulse /等待 [英] Semaphore.WaitOne/Release vs Monitor.Pulse/Wait
问题描述
对于我来说现在看起来功能 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.
这篇关于Semaphore.WaitOne /释放VS Monitor.Pulse /等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!