semaphoreos161

How semaphore value is checked using '==' operator?


A semaphore is declared and created like this --

static struct semaphore *done;
done = sem_create("done",0); // semaphore value initialized to zero

Now what happens when,

if(done==NULL)
{
     //Something done here...
}

the if condition is executed above ? since done was set to 0 do the statements inside the if block get executed ?


Solution

  • done is a pointer to semaphore, and the condition done==NULL checks whether the creation of a new semaphore succeeded, in which case done will hold the address of the new semaphore, or failed, in which case done will hold NULL.

    In short, this condition does not check the state of the semaphore, but if it was created at all.