3

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...).

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Oh ok, I missed the part of decrementing, my perception was that it waits until the value of the semaphore is equal to the value sem_wait gets (based on the order it is called). Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.