Question
In the Producer-Consumer problem, the producer writes data to a circular buffer of n slots size while the
consumer reads from it. If buffer is empty, the consumer will wait until data is available. Meanwhile, the
producer can write data only if there are any empty buffer slots. Using POSIX semaphore, write a
program to synchronize the writing and reading operations of the producer and consumer respectively.
Note: Buffer size n should be initialized by the value entered by the user on the command line.
Explanation / Answer
#include #include #include #define SHARED 1 void *Producer(void *); /* the two threads */ void *Consumer(void *); sem_t empty, full; /* the global semaphores */ int data; /* shared buffer */ int numIters; /* main() -- read command line and create threads, then print result when the threads have quit */ int main(int argc, char *argv[]) { /* thread ids and attributes */ pthread_t pid, cid; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); numIters = atoi(argv[1]); sem_init(&empty, SHARED, 1); /* sem empty = 1 */ sem_init(&full, SHARED, 0); /* sem full = 0 */ printf("main started "); pthread_create(&pid, &attr, Producer, NULL); pthread_create(&cid, &attr, Consumer, NULL); pthread_join(pid, NULL); pthread_join(cid, NULL); printf("main done "); } /* deposit 1, ..., numIters into the data buffer */ void *Producer(void *arg) { int produced; printf("Producer created "); for (produced = 0; produced