Semaphore Examples
Andrews Chapter 4
Protecting a critical region:
sem mutex =1;
process CS[i = 1 to n] {
while (true) {
P(mutex);
critical region;
V(mutex);
noncritical region;
}
}
Implementing a 2-process barrier:
sem arrive1 = 0, arrive2 = 0;
process Worker1 {
...
V(arrive1); /*signal arrival */
P(arrive2); /*await arrival of other process */
...
}
process Worker2 {
...
V(arrive2);
P(arrive1);
..
}
Implementing a simple producer/consumer
problem:
typeT buf; /* a buffer of some type */
sem empty =1; /*initially buffer is empty */
sem full = 0; /*initially buffer is not full */
process Producer [i
= 1 to m] {
while (true) {
...
/*produce data, then depositi it
in the buffer */
P(empty);
buf = data;
V(full);
}
}
process Consumer [j=1 to n] {
while (true) {
P(full);
result = buf;
V(empty);
...
}
}
Bounded Buffers: Resource Counting
typeT buf[n]; /*an array to hold the queue of messages*/
int front =0, rear =0-;
sem empty =n, full = 0; /*n -2 <= empty+full <= n*/
process Producer {
while (true) {
...
/*produce message data and deposit it in the buffer;*/
P(empty);
buf[rear] = data; rear =
(rear+1)%n;
V(full);
}
}
process Consumer {
while (true) {
/*fetch message result and consume it */
P(full);
result = buf[front]; front =
(front + 1)%n;
V(empty);
...
}
}
Implementing Multiple Producers and
Consumers
typeT buf[n] /* an array of data*/
int front =0, rear =0;
sem empty = n, full =0;
sem mutexD =1, mutexF =1; /* semaphores for mutual exclusion*/
process Producer [i= 1 to M] {
while (true) {
...
/* produce message and deposit it in the buffer */
P(empty);
P(mutexD);
buf[rear] = data; rear = (rear +1)
%n;
V(mutexD);
V(full);
}
}
process Consumer [i
= 1 to N] {
while (true) {
...
/*fetch message and consumer it */
P(full);
P(mutexF);
result = buf[front]; front =
(front+1) % n;
V(mutexF);
V(empty);
...
}
}