Facebook
From asas, 5 Months ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 126
  1.  
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <semaphore.h>
  5.  
  6. sem_t mutex, fullBuffer, emptyBuffer;
  7. int buffer = 0; // Represents the number of cokes in the machine
  8.  
  9. int main() {
  10.     sem_init(&mutex;, 0, 1);
  11.     sem_init(&fullBuffer;, 0, 0);
  12.     sem_init(&emptyBuffer;, 0, 10);
  13.  
  14.     if (fork() == 0) { // Child process represents the delivery person
  15.         for (int i = 0; i < 5; i++) { // The delivery person delivers 5 cokes
  16.             sem_wait(&emptyBuffer;);
  17.             sem_wait(&mutex;);
  18.  
  19.             // Place a coke in the machine (critical section)
  20.             buffer++;
  21.             printf("Delivery person delivered a coke. Current cokes in the machine: %d\n", buffer);
  22.  
  23.             sem_post(&mutex;);
  24.             sem_post(&fullBuffer;);
  25.         }
  26.     } else { // Parent process represents the student
  27.         for (int i = 0; i < 3; i++) { // The student wants 3 cokes
  28.             sem_wait(&fullBuffer;);
  29.             sem_wait(&mutex;);
  30.  
  31.             // Take a coke from the machine (critical section)
  32.             buffer--;
  33.             printf("Student took a coke. Current cokes in the machine: %d\n", buffer);
  34.  
  35.             sem_post(&mutex;);
  36.             sem_post(&emptyBuffer;);
  37.         }
  38.     }
  39.  
  40.     sem_destroy(&mutex;);
  41.     sem_destroy(&fullBuffer;);
  42.     sem_destroy(&emptyBuffer;);
  43.  
  44.     return 0;
  45. }
  46.  
  47.        
  48. 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:
  49.  
  50. semaphore mutex
  51. semaphore fullBuffer
  52. semaphore emptyBuffer
  53.  
  54. The following operations are available on the semaphores:
  55.  
  56. wait(semaphore s), signal(semaphore s)
  57.  
  58. Write a solution that guarantees mutual exclusion and no deadlocks. Use two functions in your code:
  59. 1. delivery_person() 2. student()
  60.  
  61. What will be the initial values of semaphores. Write code in C.
  62.  
  63.