int shared = 5
and two processes:
process 1:
int x = shared; // storing the value of shared variable in the variable x
x++;
sleep(1);
shared = x;
process 2:
int y = shared;
y--;
sleep(1);
shared = y;
Because of process synchronization, we get shared = 6 in process one and shared = 4 in process 2.
However, we want something like shared increse one at first and then decrease one. As a result this value should remain unchanged.
To solve this problem, we use semaphore.
We set a semaphore for critial section, 1 means this section is available, 0 means this sectoin is unavailable.
Here the semaphore count is the number of processes that can access the resources / code, which means “semaphore” number of processes can access this critical section at the same time. When semaphore equels zero, this critical section can not be accessed.
shared variable semaphore = 1;
process i
begin
.
.
P(mutex);
execute Critical Section
V(mutex);
.
.
end;
P(semaphore){
if semaphore is greater than 0
then decrement semaphore by 1
}
V(semaphore){
increment semaphore by 1
}