Implementation:
CSem(K) cs { // counting semaphore initialized to K
int val ← K; // the value of csem
BSem gate(min(1,val)); // 1 if val > 0; 0 if val = 0
BSem mutex(1); // protects val
Pc(cs) {
P(gate)
a1: P(mutex);
val ← val − 1;
if val > 0 V(gate);
V(mutex);
}
Vc(cs) {
P(mutex);
val ← val + 1;
if val = 1
V(gate);
V(mutex);
}
}
Another Solution:
var mutex=1: binary-semaphore;delay={min(1,initvalue)}: binary-semaphore;
C={initvalue}: integer;
Procedure Wait()
begin
wait(delay);
wait(mutex);
C:=C-1;
if C>0 then
signal(delay);
signal(mutex);
end
Procedure Signal()
begin
wait(mutex);
C:=C+1;
if C=1 then
signal(delay)
signal(mutex)
end
Conclusions
• The implementation of general semaphores using binary semaphores must be implemented carefully so no concurrency errors are introduced• Various solutions exist, when choosing a solution examine the performance characteristics of each that best suits your needs
• Implementation of general semaphores using binary semaphores is not recommended when efficiency is a concern
Comments
Post a Comment