将 POSIX 信号量的值增加超过 1
我有这样的要求,其中我必须将 POSIX 信号量的值增加超过 1。
显然,POSIX 规范中没有办法做到这一点。没有类似于 sem_getvalue() 的 sem_setvalue()。我不想仅仅因为这个限制而回到 System V 信号量。
有没有其他方法可以实现这一点?或者我必须采用 System V 方式吗?
我正在 GNU/Linux 上使用 C 进行编程。
非常感谢。
I have this requirement wherein I have to increment the value of a POSIX semaphore by more than 1.
Apparently, there is no way in POSIX specification to do this. There is no sem_setvalue() similar to sem_getvalue(). I do not want to go back to System V semaphores just because of this constraint.
Is there any alternative way to accomplish this? Or will I have to go the System V way?
I am programming in C on GNU/Linux.
Great thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
那么你的问题到底是什么?如何实现接口不支持的东西?或者如何使用 POSIX 创建行为类似于 信号量 的结构?
如果这是稍后的事情,那么在诉诸 SysV 之类的重型武器之前,您始终可以使用
pthread_mutex_t
/pthread_cond_t
对来实现几乎任何多线程同步原语,包括信号量。例如,未经测试:
So what is your question really? How to implement something not supported by interface? Or how to create a structure behaving like semaphore using POSIX?
If this is later, before resorting to heavy guns like SysV, you can always use the
pthread_mutex_t
/pthread_cond_t
pair to implement pretty much any multi-threading synchronization primitive, semaphore included.E.g., untested:
semctl
和semop
是您所需要的。在 smectl 中使用 GETVAL SETVAL 来获取 getter 和 setter。将 sembuf 结构中的 sem_op 设置为您想要执行的操作使用 semop 时与信号量一起使用。更多信息请参见男人。semctl
andsemop
are what you need.Use GETVAL SETVAL in smectl for getter and setter.Set sem_op in sembuf struct to what you want to do with the semaphore when using semop. See man for more.不,使用
sem_t
时没有这样的选择。如果您还没有这样做,请阅读 Linux 上的sem_overview
手册页。列出的调用是您可以获得的所有调用:初始化为特定值、递增和递减 1。No there is no such alternative when working with
sem_t
. If you have not yet done so, read thesem_overview
man page on linux. The calls that are listed there are all you can get: initialization to a specific value, increment and decrement by one.如果这是完整的规范,我认为你的老师希望你想出一种机制,允许你以原子方式将信号量增加一个以上。所以我的猜测是你的任务之一是同步增量。
If that is the complete specification, I think your teacher wants you to come up with a mechanism that will allow you to increment a semaphore by more than one atomically. So my guess is that one of your tasks is to synchronize the incrementation.