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之后才可以被使用。
参考:http://stackoverflow.com/questions/1221322/how-does-semaphore-work
Calling down when it's 0 should not work. Calling up when it's 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).
相关推荐
semaphore完整搭建方案,包括帮助文档、程序源码、可执行程序。按照帮助文档完整搭建可视化ansible部署解决方案
semaphore开发源码,ansible可视化部署服务程序,支持界面操作。
Semaphore的使用及其方法的使用。
Semaphore T-BOX System OverviewPDF,Semaphore T-BOX System Overview
mutex和semaphore互斥程序实例
Semaphore 源码解析 通过使用Semaphore可以在高并发场景进行限流控制处理
关于Android变成中的信号量semaphore,在使用过程中我们往往搞不清楚其信号量的申请和使用。这里主要针对信号量初始值为零的情况做介绍,其他情况不做讨论。初始值为零的情况较少使用,部分代码中的这个情况往往让...
Semaphore是计数信号量。Semaphore管理一系列许可证。每个acquire方法阻塞,直到有一个许可证可以获得然后拿走一个许可证;每个release方法增加一个许可证,这可能会释放一个阻塞的acquire方法。然而,其实并没有...
Semaphore_TBOX_产品-软件及系统功能
semaphore控制多线程循序执行,网上 找的例子更改的希望对大家有用
使用信号量(Semaphore)实现线程的同步
Linux下多线程编程-Pthread与Semaphore的使用.doc
多线程(C++)同步Semaphore
Semaphore进程间通讯测试源码,CreateSemaphoreW,OpenSemaphore,ReleaseSemaphore,WaitForSingleObjectEx
windows下安装cygwin,编译darknet时缺少的三个头文件,下载后复制到darknet下include文件夹内即可
信号量+共享存储区的进程间通信,互斥、同步
本文分析了内核同步及互斥的几种机制Waitqueue、Event及Semaphore的实现,详细分析了其实现流程。Event及Semaphore本质上都是基于Waitqueue和自旋锁实现的。总结了静态定义及动态初始化数据结构的相关规则,这对于...
Ansible-semaphore.zip,可供选择的开源towerrelease,ansible是一个简单而强大的自动化引擎。它用于帮助配置管理、应用程序部署和任务自动化。
C#语言Semaphore类用法实例,多线程 用于有多个同类型共享资源(比如端口)时,如何协调端口分配给线程访问资源的问题,是一个简单模拟实例(源代码)。
当前版本包括以下变量: 名称默认值描述semaphore_user_name 信号运行信号量服务的用户名semaphore_group_name 信号运行信号量服务的组名semaphore_user_uid 1000 Semaphore 服务用户的 UID semaphore_group_gid ...