Semaphore释疑csdn - 娱乐之横扫全球

Semaphore释疑csdn

2019-02-10 07:06:03 | 作者: 惜蕊 | 标签: 信号,运用,信号量 | 浏览: 6148

java api中Semaphore(信号量),用于操控有限资源的并发拜访。API也非常好了解,不过有几个需求留意的当地:

Semaphore是朴实的运用级操控“锁”,运用简略的volitale变量作为信号量信息,通过acquire、release、reduce等显式的能够修正此信号量数字。 它并没有保护任何锁,也不是操控reentrant的,它不会保护信号和thread的联系。 Semaphore的初始值能够为0,乃至能够为负数。关于acquire调用(信号down),它只会比较现在信号值与0的巨细联系,假如 =0那么将不能取得授权。 关于release(信号up),仅仅简略的对信号值进行原子添加,通过屡次的release,信号值能够超越初始的阀值。 关于Semaphore(0/-N)的场景,有特别的运用,这种信号操控,在能够acquire之前,有必要通过约好的足够多的release之后才能够被运用。

参阅:https://stackoverflow.com/questions/1221322/how-does-semaphore-work

 

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

 

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().

 

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.

 

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).

 

版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表娱乐之横扫全球立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章