Reputation: 355
I am working on semaphores in Linux. I would like to know if the semaphore value can ever be incremented beyond the initialized value? If so, when can that happen?
For example, semaphore value is initialized to 1. If I increment twice continuously using up(sem), will the value of semaphore increment beyond 1.
x(void){
sema_init(sem1, 1);
down(sem1);
{
.
. // some code implementation
.
}
up(sem1); // i understand this increment the value back to 1.
up(sem1);
/* what exactly does this statement do to the semaphore?
Will it increment the value to 2? If so what is the meaning of this statement? */
}
Upvotes: 1
Views: 2065
Reputation: 14046
Yes it will increment it to 2. The effect is that the next two semaphore down calls will run without blocking. The general use case of semaphores is to protect a pool of resources. If there is 1 resource then the max expected value of the semaphore will be 1. If there are 2 resources then max expected value is 2 and so on. So whether incrementing the semaphore to 2 is correct or not depends upon the context. If only 1 process should get past the semaphore at any given time then incrementing to 2 is a bug in the code. If 2 or more processes are allowed then incrementing to 2 is allowable.
This is a simplified explanation. For more details look up "counting semaphores". The other type of semaphore which you may be thinking of is "binary semaphores" which are either 0 or 1.
Upvotes: 4