The Producer/Consumer (Bounded Buffer) Problem
Remember the producer/consumer problem from the previous chapter? Let's try to solve it with semaphores!
We'll cover the following...
The next problem we will confront in this chapter is known as the producer/consumer problem, or sometimes as ...
int buffer[MAX];int fill = 0;int use = 0;void put(int value) {buffer[fill] = value; //Line F1fill = (fill + 1) % MAX; //Line F2}int get() {int tmp = buffer[use]; // Line G1use = ( use + 1) % MAX; //Line G2return tmp;}
Our attempt at solving the producer and consumer problem is in the code snippet below.
sem_t empty;sem_t full;void *producer(void *arg) {int i;for (i = 0; i < loops; i++) {sem_wait(&empty); //Line P1put(i); //Line P2sem_post(&full); //Line P3}}void *consumer(void *arg) {int i,tmp = 0;while (tmp != -1) {sem_wait(&full); //Line C1tmp = get(); //Line C2sem_post(&empty); //Line C3printf("%d\n", tmp);}}int main(int argc, char *argv[]) {// ...sem_init(&empty, 0, MAX); // MAX are emptysem_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 ...
Ask