Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sem_init(…): What is the value parameter for?

In a class, we've had to use semaphores to accomplish work with threads. The prototype (and header file) of sem_init is the following:

int sem_init(sem_t *sem, int pshared, unsigned int value);

but I don't understand what the value variable is used for. According to opengroup.org:

value is an initial value to set the semaphore to

"value is a value..." How does that help, what is it used for?

like image 561
Gabriel Fair Avatar asked Feb 20 '12 23:02

Gabriel Fair


People also ask

What is Sem_init value?

The sem_init() function initializes an unnamed semaphore and sets its initial value. The maximum value of the semaphore is set to SEM_VALUE_MAX. The title for the semaphore is set to the character representation of the address of the semaphore.

What is the first parameter for Sem_init ()?

sem_init() initializes a pointed to semaphore (first parameter), with value (last parameter), and finally I believe this is actually what you were asking, int pshared you can think of like a flag. If pshared == 1 then semaphore can be forked.

What does Sem_init return?

sem_init() returns zero after completing successfully. Any other return value indicates that an error occurred. When any of the following conditions occurs, the function fails and returns the corresponding value. EINVAL.

How do you find the value of semaphores?

The sem_getvalue() function retrieves the value of a named or unnamed semaphore. If the current value of the semaphore is zero and there are threads waiting on the semaphore, a negative value is returned. The absolute value of this negative value is the number of threads waiting on the semaphore.


2 Answers

Semaphore value represents the number of common resources available to be shared among the threads. If the value is greater than 0, then the thread calling sem_wait need not wait. It just decrements the value by 1 and proceeds to access common resource. sem_post will add a resource back to the pool. So it increments the value by 1. If the value is 0, then we will wait till somebody has done sem_post.

like image 123
user3456677 Avatar answered Sep 17 '22 12:09

user3456677


sem_init() initializes a pointed to semaphore (first parameter), with value (last parameter), and finally I believe this is actually what you were asking, int pshared you can think of like a flag. If pshared == 1 then semaphore can be forked.

EDIT: semaphore has int value because you would use a function such as sem_wait(sem_t* sem) to decrement pointed to semaphore. If it's negative, then block.

like image 31
Zachary Friedman Avatar answered Sep 19 '22 12:09

Zachary Friedman