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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With