信号量如何工作? [英] How does semaphore work?

查看:433
本文介绍了信号量如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

信号量可以低于0吗?我的意思是,我说我有一个N = 3的信号量,然后我叫向下4次,然后N将保持0但是一个进程将被阻止?

Can the semaphore be lower than 0? I mean, say I have a semaphore with N=3 and I call "down" 4 times, then N will remain 0 but one process will be blocked?

同样另一方面,如果在开始我打电话,N可以高于3吗?因为正如我所看到的那样,如果N在开始时我可以多次调用3次,那么稍后我可以调用更多次,因此在关键部分放入更多进程然后信号量允许我。

And same the other way, if in the beginning I call up, can N be higher than 3? Because as I see it, if N can be higher than 3 if in the beginning I call up couple of times, then later on I could call down more times than I can, thus putting more processes in the critical section then the semaphore allows me.

如果有人为我澄清一点,我会非常感激。

If someone would clarify it a bit for me I will much appreciate.

Greg

推荐答案

当它为0时调用不应该工作。在3的时候调用它确实有效。 (我在想Java)。

Calling down when it's 0 should not work. Calling up when it's 3 does work. (I am thinking of Java).

让我再添加一些。许多人会想到像(二进制)信号量这样的锁(即 - N = 1,因此信号量的值为0(保持)或1(不保持))。但这不太对。锁具有所有权的概念,因此它可能是可重入的。这意味着一个持有锁的线程被允许再次调用lock()(有效地将计数从0移动到-1),因为线程已经持有锁并被允许重新进入它。锁也可以是不可重入的。锁定持有者应该与lock()调用unlock()的次数相同。

Let me add some more. Many people think of locks like (binary) semaphores (ie - N = 1, so the value of the semaphore is either 0 (held) or 1 (not held)). But this is not quite right. A lock has a notion of "ownership" so it may be "reentrant". That means that a thread that holds a lock, is allowed to call lock() again (effectively moving the count from 0 to -1), because the thread already holds the lock and is allowed to "reenter" it. Locks can also be non reentrant. A lock holder is expected to call unlock() the same number of times as lock().

信号量没有所有权的概念,因此它们不能是可重入的,尽管可以获得许多许可证。这意味着线程在遇到值0时需要阻塞,直到有人递增信号量。

Semaphores have no notion of ownership, so they cannot be reentrant, although as many permits as are available may be acquired. That means a thread needs to block when it encounters a value of 0, until someone increments the semaphore.

此外,在我所看到的(这是Java)中,你可以增加大于N的信号量,这也与所有权有关:信号量没有所有权的概念,所以任何人都可以给它更多的许可。与线程不同,每当线程调用unlock()而不保持锁定时,这就是错误。 (在java中它会引发异常)。

Also, in what I have seen (which is Java), you can increment the semaphore greater than N, and that also sort of has to do with ownership: a Semaphore has no notion of ownership so anybody can give it more permits. Unlike a thread, where whenever a thread calls unlock() without holding a lock, that is an error. (In java it will throw an exception).

希望这种思考方式有所帮助。

Hope this way of thinking about it helps.

这篇关于信号量如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆