我有这个要求,其中我必须增加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.
Is there any alternative way to accomplish this? Or will I have to go the System V way?
那你的问题到底是什么?如何实现接口不支持的东西?或者如何使用POSIX创建一个类似于semaphore的结构?
如果这是稍后,在使用像SysV这样的重枪之前,你总是可以使用pthread_mutex_t / pthread_cond_t对来实现几乎任何包含信号量的多线程同步原语.
例如,未经测试:
typedef cool_sem {
pthread_mutex_t guard;
pthread_cond_t cond;
int count;
} cool_sem_t;
void init( cool_sem_t *s )
{
pthread_mutex_init( &s->guard, 0 );
pthread_cond_init( &s->cond, 0 );
s->S = 0;
}
void incr( cool_sem_t *s, unsigned delta )
{
assert( s );
pthread_mutex_lock( &s->guard );
s->S += delta;
pthread_cond_broadcast( &s->cond );
pthread_mutex_unlock( &s->guard );
}
void decr( cool_sem_t *s, unsigned delta )
{
assert( s );
pthread_mutex_lock( &s->guard );
do {
if (s->S >= delta) {
s->S -= delta;
break;
}
pthread_cond_wait( &s->cond, &s->guard );
} while (1);
pthread_mutex_unlock( &s->guard );
}