10
votes

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?

3

3 Answers

5
votes

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.

1
votes

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.

1
votes

In order to understand the "value" in sem_init(sem_t *sem, int pshared, unsigned int value)

I think we need synchronize it with how we use the semaphore in codes: when we want to wait for the semaphore, we call sem_wait (&mutex), and if we want to notify to make other threads' sem_wait (&mutex) run, we need call sem_post (&mutex). But the problem is if no any other threads call sem_post (&mutex) at first(in the system initialization), what should the sem_wait (&mutex) do? It should pass or wait for other threads call sem_post (&mutex)? The answer is in the "value" in the sem_init(). If it's zero, it means we must wait for some other threads to call sem_post() one time, then it could pass. If it's one, then the first time calling for sem_wait() will pass at once, but the second time sem_wait() will wait(if no sem_post called during them). So the value in sem_init() means how many times we could execute sem_wait() without really waiting without any sem_post(). And we could consider the sem_wait() as: /deadlock waiting until value is changed to bigger than 0 by another thread/

while (value<=0) {}

value--;

And consider the sem_post() as:

value++;