Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
865 views
in Technique[技术] by (71.8m points)

c - Incrementing the value of POSIX semaphores by more than 1

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

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:

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 );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...