0

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 ?

Pavel
  • 138
  • 2
  • 4
  • 16

2 Answers2

2

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.

MByD
  • 135,866
  • 28
  • 264
  • 277
1

I am answering this question with respect to OS161 implementations. done is a pointer to semaphore and it would be NULL only when the sem_create does not create the semaphore due to memory not available or other memory constraints.

The 0 value that is passed as a parameter to a function which initializes the initial count of semaphore to be 0. The count can be accessed as done->count and then a particular code can be executed depending on the count value.

While coding for OS161 I solved a few synch problems using semaphores, you could check them out at the link given below:

https://github.com/prathammalik/OS161/tree/master/kern/synchprobs

n3wcod3r
  • 114
  • 10