Wilhelm Sorban
Wilhelm Sorban

Reputation: 1131

Semaphore values in c

If I understand correctly, from this post: http://www.csc.villanova.edu/~mdamian/threads/posixsem.html

Then after each thread passes from sem_wait(&sem1) because of an sem_post(&sem1) from somewhere else, the value of the semaphore should increment. So if I do:

    sem_wait(&sem1);
    int sval2;
    if (sem_getvalue(&sem1, &sval2) == 0){
        printf("Semaphore value: %d\n", sval2);
    }   

With

sem_init(&sem1, 0, 0);

Executed previously, my output should be:

1
2
3
4
etc......

I am asking this, because in my project, the events seem to be following the correct order, but when I do the sem_getvalue, the output on some semaphores stay constant (0), at others goes +1 once, then stays constant (1), and on others it goes up and down (1, then 3, then 4, then 5, then 3, etc...).

Upvotes: 3

Views: 6745

Answers (2)

hobbs
hobbs

Reputation: 240581

sem_post increments, sem_wait decrements (and blocks until the semaphore has a positive value, so as not to decrement it below zero). The values you observe with sem_getvalue will depend on the order that the threads run and the order of the various increments and decrements.

Upvotes: 1

psmears
psmears

Reputation: 28110

sem_post increases the value of a semaphore by one. sem_wait decrements a semaphore's value (decreases it by one), provided that won't make it go below zero (otherwise it blocks). (See man sem_wait for more technical details.)

The values you are seeing are due to the order that sem_wait and sem_post are being called.

Upvotes: 1

Related Questions