# Show how the number of semaphores can be implemented using only binary semaphores and ordinary instructions of the machine?

I am studying for a midterm and this was one of the practice questions: Show how counting semaphores (i.e, semaphores that can hold an arbitrary value) can be implemented using only binary semaphores and ordinary machine instructions?

I'm not even sure where so start. I found this online;

``````P(s) { Pb(mutex_s); s = s-1; if(s < 0) {Vb(mutex_s); Pb(delay_s);} Vb(mutex_s); }
V(s) { Pb(mutex_s); s = s+1; if(s <= 0) Vb(delay_s); else Vb(mutex_s); }
```
```

Unfortunately, I don't really understand what the answer is telling me. Can anyone explain this answer to me, or show me in pseudo code how to answer?

``````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);
}
}
```
```