The bounded buffer

A bounded buffer is shared by a producer and a consumer. The semaphore empty counts free slots and full counts filled ones. A producer that finds empty at 0 must wait, and so must a consumer that finds full at 0.

What to build

Run a list of produce and consume events on a buffer with N slots, and report what happens at each one.

Requirements

  • P x puts the number x in the buffer if there is a free slot and prints stored x; if the buffer is full it prints full and changes nothing.
  • C takes out the oldest item (first in, first out) and prints consumed x; if the buffer is empty it prints empty and changes nothing.
  • At the end print items: K and full=F empty=E, the number of items and the values the two semaphores would have.

Input

The first line has N (1 ≤ N ≤ 8) and q (1 ≤ q ≤ 40). Then q lines, each P x (x from 0 to 1000) or C.

Output

One line for each event, then the items: line and the full= line.

Constraints

full plus empty is always N.

Example

Input:

3 6
P 10
P 20
C
P 30
P 40
P 50

Output:

stored 10
stored 20
consumed 10
stored 30
stored 40
full
items: 3
full=3 empty=0

Why it works

The two semaphores always add up to N, because every slot is either full or empty. The circular index wraps with %, so the buffer reuses its slots, and the items come out in the order they went in.

Examples

Example 1 · Input
3 6
P 10
P 20
C
P 30
P 40
P 50
Expected output
stored 10
stored 20
consumed 10
stored 30
stored 40
full
items: 3
full=3 empty=0
Example 2 · Input
2 3
C
P 7
C
Expected output
empty
stored 7
consumed 7
items: 0
full=0 empty=2

Hints

Hint 1

Keep an array of N slots used as a circular queue: in, out and a count of items.

Hint 2

Produce into a full buffer prints full and changes nothing; consume from an empty one prints empty.

Hint 3

The semaphore values are full = count and empty = N - count.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int main(void) {
    int cap, q, x, buffer[8], in = 0, out = 0, count = 0;
    char op;
    scanf("%d %d", &cap, &q);
    for (int i = 0; i < q; i++) {
        scanf(" %c", &op);
        if (op == 'P') {
            scanf("%d", &x);
            if (count == cap) {
                printf("full\n");
            } else {
                buffer[in] = x;
                in = (in + 1) % cap;
                count++;
                printf("stored %d\n", x);
            }
        } else {
            if (count == 0) {
                printf("empty\n");
            } else {
                printf("consumed %d\n", buffer[out]);
                out = (out + 1) % cap;
                count--;
            }
        }
    }
    printf("items: %d\n", count);
    printf("full=%d empty=%d\n", count, cap - count);
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Synchronization: locks and semaphores →