免费注册 查看新帖 |

Chinaunix

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

关于信号量SEM_UNDO标志的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-04-17 10:35 |只看该作者 |倒序浏览
sem_lock() 和 sem_unlock() 都指定SEM_UNDO标志了
信号灯0:表示同一时间只有1个A资源可以使用
信号灯1:表示同一时间只有1个B资源可以使用

管理进程(进程1):
   // 初始有1个可用的A资源
   sem_unlock( 0 );

进程2(在进程1运行后创建):
   // 等待A资源可用
   sem_lock( 0 );
   ......
   
   // 释放B资源, 唤醒进程3
   sem_unlock( 1 );
   .....
   <D区域>
   .....

进程3:
   // 等待B资源
   sem_lock( 1 );
   ......
   
   // 释放A资源
   sem_unlock( 0 );
   ......

问题:当进程2在“d区域”异常退出(coredown)时,查看信号灯0的值, 变成"2"了?

针对进程2(工作进程)异常退出或主动kill掉,信号灯0的值又不想还原回去,不知各位大虾
有啥好的改进意见?

网上还搜到了一段话,针对信号量p操作,进程会保留调整值semadj, 在进程异常退出时会自动调整还原。
As we mentioned earlier, it is a problem if a process terminates
while it has resources allocated through a semaphore.
Whenever we specify the SEM_UNDO flag for a semaphore
operation and we allocate resources (a sem_op value less than 0),
the kernel remembers how many resources we allocated from
that particular semaphore (the absolute value of sem_op).
When the process terminates, either voluntarily or involuntarily,
the kernel checks whether the process has any outstanding semaphore
adjustments and, if so, applies the adjustment to the corresponding semaphore.

  1. int get_sem_val( int sem_id, int sem_slot )
  2. {
  3.         union semun arg;
  4.         return semctl( sem_id, sem_slot, GETVAL,arg );
  5. }

  6. int sem_lock( int sem_id, int sem_slot )
  7. {
  8.         union semun                arg;
  9.         struct sembuf         waittop;
  10.         waittop.sem_num = sem_slot;
  11.         waittop.sem_op = -1;
  12.         waittop.sem_flg = SEM_UNDO;
  13.        
  14.         if( semop( sem_id,&waittop,1 ) == -1 ) {
  15.                 arg.val = get_sem_val( sem_id, sem_slot ) - 1;
  16.                 return semctl( sem_id, sem_slot, SETVAL,arg );
  17.         }
  18.        
  19.         return 0;
  20. }

  21. int  sem_unlock(int sem_id, int sem_slot)
  22. {
  23.         union semun                arg;
  24.         struct sembuf         postop;
  25.         postop.sem_num = sem_slot;
  26.         postop.sem_op  = 1;
  27.         postop.sem_flg = SEM_UNDO;
  28.        
  29.         if( semop(sem_id,&postop,1 ) == -1 ) {
  30.                 arg.val = semctl( sem_id, sem_slot, GETVAL,0 )+1;
  31.                 semctl( sem_id, sem_slot, SETVAL, arg );
  32.         }
  33. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP