Reputation: 205
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
S--;
}
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?
Upvotes: 3
Views: 6541
Reputation: 25895
Please have a look at http://man7.org/linux/man-pages/man3/sem_init.3.html. Regarding the second argument:
The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes.
This is essentially Boolean, but read the link for more info. If you're really threading than this should always be 0, in extreme cases you use threading code on different processes use non-zero.
Upvotes: 1
Reputation: 433
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
Upvotes: 1