免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3308 | 回复: 2
打印 上一主题 下一主题

semaphore 中s是否能为负值 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-06-11 17:18 |只看该作者 |倒序浏览
在wiki上面看到的几篇文章都明确说
s不能为负值,   因为s表示某种资源可用的数量, 最小为0
http://en.wikipedia.org/wiki/Monitor_(synchronization) 中介绍使用monitor实现semaphore时
However, the integer must never be decremented below 0; thus a thread that tries to decrement must wait until the integer is positive.


http://en.wikipedia.org/wiki/Semaphore_(programming)
中定义p操作时
  1. function V(semaphore S):
  2.     Atomically increment S
  3.     [S ← S + 1]

  4. function P(semaphore S):
  5.     repeat:
  6.         Between repetitions of the loop other processes may operate on the semaphore
  7.         [if S > 0:
  8.             Atomically decrement S - note that S cannot become negative
  9.             S ← S - 1
  10.             break
复制代码
但课本上面还有网上查的中文资料里面都是 s可以为负值
P操作的定义是先s-- 然后测试s是否大于等于0  

按照semaphore的定义(按照wiki上的) s小于0是没有意义的

但课本上用s为负值表示等待此资源的进程数目  (看起来也是很有意义的)

想请教下各位  现实中(一般操作系统提供的PV) 中  s是否可以为负.  

(完全用linux都快4年了,但都还没接触过内核,上课之后才知道signal和wait竟然就是PV...   惭愧中)

论坛徽章:
0
2 [报告]
发表于 2011-06-11 18:54 |只看该作者
signal应该不是pv吧。。。

但课本上用s为负值表示等待此资源的进程数目  (看起来也是很有意义的)
好像LINUX就是这么实现的。。。

论坛徽章:
0
3 [报告]
发表于 2011-06-12 20:05 |只看该作者
本帖最后由 SNYH 于 2011-06-12 20:06 编辑

看了下 man 3 sem_getvalue中的一句
If one or more processes or threads are blocked  waiting  to  lock  the
semaphore  with sem_wait(3), POSIX.1-2001 permits two possibilities for
the value returned in sval: either 0 is returned; or a negative  number
whose  absolute  value  is  the  count  of  the number of processes and
threads currently blocked in  sem_wait(3).
  Linux  adopts  the  former
behavior.

看来两种方式都是存在的.  不过linux adopts the former behavior.  这句看来
linux是选择wiki上面的方式吧?

不纠结这个问题了,  
wiki上面解释的意义和实际实现方式属于不同层面上的事物, semaphore意义应该就是wiki上写的, wiki上面的那个PV具体操作属于实现的其中一种.
课本上的属于另外一种实现,或者semaphore的变种.
(自我安慰中)

关于signal, 表示很羞愧.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP