NaveeNeo NaveeNeo - 9 months ago 56
C Question

What are the meanings of parameters passed to sem_init() in Semaphores(Operating Systems)?

Consider the code snippet given below :

#include <pthread.h>
#include <semaphore.h>

sem_t empty;
sem_t full;
sem_t mutex;

int main(int argc, char *argv[])
int MAX = 10;//Size of the Buffer
sem_init(&empty, 0, MAX);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);

return 0;

Only the required code,I have mentioned above. It's a part of Producer-Consumer Code. What are the meanings of each parameters in sem_init()? I could make out that 1st parameter is the address of the semaphore variable and 3rd one is it's value.

Why the 2nd parameter is always 0? What does that mean?

Are we specifying critical value for the semaphore to wait using 2nd parameter?

wait(S) {
while (S <= 0 )
; // busy wait

If I pass 3 as 2nd parameter to sem_init(), does the while loop in wait(S) will be changed to

while (S <= 3 )

like this?

Answer Source

Always try to read Linux documentation(man <command or system_call>) for these type of doubts.

for your case man sem_init
sem_init() initializes the unnamed semaphore at the address pointed to by sem. The value argument specifies the initial value for the semaphore.

web link of the man pages