Search⌘ K
AI Features

The Producer/Consumer (Bounded Buffer) Problem

Explore the producer consumer problem using semaphores to synchronize thread actions and manage a finite buffer. Understand how the producer waits for empty slots while the consumer waits for filled slots, ensuring safe concurrent access and avoiding race conditions in operating systems.

We'll cover the following...

The next problem we will confront in this chapter is known as the ...

C
int buffer[MAX];
int fill = 0;
int use = 0;
void put(int value) {
buffer[fill] = value; //Line F1
fill = (fill + 1) % MAX; //Line F2
}
int get() {
int tmp = buffer[use]; // Line G1
use = ( use + 1) % MAX; //Line G2
return tmp;
}

Our attempt at solving the producer and consumer problem is in the code snippet below.

C
sem_t empty;
sem_t full;
void *producer(void *arg) {
int i;
for (i = 0; i < loops; i++) {
sem_wait(&empty); //Line P1
put(i); //Line P2
sem_post(&full); //Line P3
}
}
void *consumer(void *arg) {
int i,tmp = 0;
while (tmp != -1) {
sem_wait(&full); //Line C1
tmp = get(); //Line C2
sem_post(&empty); //Line C3
printf("%d\n", tmp);
}
}
int main(int argc, char *argv[]) {
// ...
sem_init(&empty, 0, MAX); // MAX are empty
sem_init(&full, 0, 0); // 0 are full
// ...
}

In this example, the producer first waits for a buffer to become empty in order to put data into it, and the consumer similarly waits for a buffer to become filled before using it. Let us ...