Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise a binary semaphore in C

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 incremented to a value greater than 1 with multiple calls to

sem_post(&mySem);

But in this code example the comment seems to think differently:

sem_init(&mutex, 0, 1);      /* initialize mutex to 1 - binary semaphore */

Is it possible to initialise a strictly binary semaphore in C?

Note: The reason for doing this instead of using a mutex in this case is the sem_post and sem_wait may be called by different threads.

like image 377
austinmarton Avatar asked Sep 19 '11 23:09

austinmarton


People also ask

How do you initialize a semaphore?

Use sema_init(3THR) to initialize the semaphore variable pointed to by sem to value amount. If the value of pshared is zero, then the semaphore cannot be shared between processes. If the value of pshared is nonzero, then the semaphore can be shared between processes. (For Solaris threads, see "sema_init(3THR)".)

What is the correct way to initialise the semaphore to 1?

/* Code Listing 7.10: Initializing a semaphore for mutual exclusion instead of signaling */ /* For mutual exclusion, initialize the semaphore to 1 */ sem_t *sem = sem_open ("/OpenCSF_Sema", O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 1); assert (sem !=


1 Answers

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);
}
like image 198
Dietrich Epp Avatar answered Sep 19 '22 08:09

Dietrich Epp