A counting semaphore holds a number of free resources. wait takes one, and a thread that finds none must block. signal gives one back, and wakes a blocked thread if there is one.
What to build
Apply a list of wait and signal operations to one semaphore, and print its value and the number of blocked threads.
Requirements
- The semaphore starts with value
s0.Wis a wait: if the value is above 0 it goes down by 1 and the wait passes at once; otherwise the calling thread blocks. Sis a signal: if some thread is blocked, one of them wakes up (the number blocked goes down by 1 and the value stays the same); otherwise the value goes up by 1.- Print
value: V,blocked: Bandpassed: P, wherePis the number of waits that passed at once.
Input
The first line has s0 (0 to 10) and n (1 ≤ n ≤ 50). The second line has n letters, each W or S, separated by spaces.
Output
Three lines: value: V, blocked: B, passed: P.
Constraints
A woken thread is not counted as passing at once.
Example
Input:
2 5
W W W S S
Output:
value: 1
blocked: 0
passed: 2
Why it works
When a signal wakes a blocked thread, the resource goes straight to that thread, so the value does not change; the value counts only free units that nobody is waiting for. Value and blocked count are never both above zero.
Examples
2 5 W W W S S
value: 1 blocked: 0 passed: 2
0 3 S S W
value: 1 blocked: 0 passed: 1
Hints
Hint 1
Keep three numbers: the semaphore value, the number of blocked threads, and how many waits passed at once.
Hint 2
A wait with value above 0 lowers the value and passes. A wait with value 0 adds one blocked thread.
Hint 3
A signal with blocked threads wakes one (blocked goes down, the value stays). A signal with none waiting adds 1 to the value.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int s0, n, value, blocked = 0, passed = 0;
char op;
scanf("%d %d", &s0, &n);
value = s0;
for (int i = 0; i < n; i++) {
scanf(" %c", &op);
if (op == 'W') {
if (value > 0) {
value--;
passed++;
} else {
blocked++;
}
} else {
if (blocked > 0) blocked--;
else value++;
}
}
printf("value: %d\n", value);
printf("blocked: %d\n", blocked);
printf("passed: %d\n", passed);
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step