#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
sem_t mutex, fullBuffer, emptyBuffer;
int buffer = 0; // Represents the number of cokes in the machine
int main() {
sem_init(&mutex;, 0, 1);
sem_init(&fullBuffer;, 0, 0);
sem_init(&emptyBuffer;, 0, 10);
if (fork() == 0) { // Child process represents the delivery person
for (int i = 0; i < 5; i++) { // The delivery person delivers 5 cokes
sem_wait(&emptyBuffer;);
sem_wait(&mutex;);
// Place a coke in the machine (critical section)
buffer++;
printf("Delivery person delivered a coke. Current cokes in the machine: %d\n", buffer);
sem_post(&mutex;);
sem_post(&fullBuffer;);
}
} else { // Parent process represents the student
for (int i = 0; i < 3; i++) { // The student wants 3 cokes
sem_wait(&fullBuffer;);
sem_wait(&mutex;);
// Take a coke from the machine (critical section)
buffer--;
printf("Student took a coke. Current cokes in the machine: %d\n", buffer);
sem_post(&mutex;);
sem_post(&emptyBuffer;);
}
}
sem_destroy(&mutex;);
sem_destroy(&fullBuffer;);
sem_destroy(&emptyBuffer;);
return 0;
}
Consider a coke machine that has 10 slots. The producer is the delivery person and the consumer is the student who is thirsty and wants to use the machine to get a coke. We use the following three semaphores:
semaphore mutex
semaphore fullBuffer
semaphore emptyBuffer
The following operations are available on the semaphores:
wait(semaphore s), signal(semaphore s)
Write a solution that guarantees mutual exclusion and no deadlocks. Use two functions in your code:
1. delivery_person() 2. student()
What will be the initial values of semaphores. Write code in C.
{"html5":"htmlmixed","css":"css","javascript":"javascript","php":"php","python":"python","ruby":"ruby","lua":"text\/x-lua","bash":"text\/x-sh","go":"go","c":"text\/x-csrc","cpp":"text\/x-c++src","diff":"diff","latex":"stex","sql":"sql","xml":"xml","apl":"apl","asterisk":"asterisk","c_loadrunner":"text\/x-csrc","c_mac":"text\/x-csrc","coffeescript":"text\/x-coffeescript","csharp":"text\/x-csharp","d":"d","ecmascript":"javascript","erlang":"erlang","groovy":"text\/x-groovy","haskell":"text\/x-haskell","haxe":"text\/x-haxe","html4strict":"htmlmixed","java":"text\/x-java","java5":"text\/x-java","jquery":"javascript","mirc":"mirc","mysql":"sql","ocaml":"text\/x-ocaml","pascal":"text\/x-pascal","perl":"perl","perl6":"perl","plsql":"sql","properties":"text\/x-properties","q":"text\/x-q","scala":"scala","scheme":"text\/x-scheme","tcl":"text\/x-tcl","vb":"text\/x-vb","verilog":"text\/x-verilog","yaml":"text\/x-yaml","z80":"text\/x-z80"}