How to initialise a binary semaphore in C

前端 未结 1 1344
闹比i
闹比i 2020-12-17 20:58

In the man page it appears that even if you initialise a semaphore to a value of one:

sem_init(&mySem, 0, 1);

It could still be increme

相关标签:
1条回答
  • 2020-12-17 21:22

    If you want a strictly binary semaphore on Linux, I suggest building one out of mutexes and condition variables.

    struct binary_semaphore {
        pthread_mutex_t mutex;
        pthread_cond_t cvar;
        bool v;
    };
    
    void mysem_post(struct binary_semaphore *p)
    {
        pthread_mutex_lock(&p->mutex);
        if (p->v)
            abort(); // error
        p->v = true;
        pthread_cond_signal(&p->cvar);
        pthread_mutex_unlock(&p->mutex);
    }
    
    void mysem_wait(struct binary_semaphore *p)
    {
        pthread_mutex_lock(&p->mutex);
        while (!p->v)
            pthread_cond_wait(&p->cvar, &p->mutex);
        p->v = false;
        pthread_mutex_unlock(&p->mutex);
    }
    
    0 讨论(0)
提交回复
热议问题