Advertisement
Bewin

semaphore

Apr 9th, 2024
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <semaphore.h>
  5. #include <unistd.h>
  6.  
  7. #define BUFFER_SIZE 5
  8.  
  9. int buffer[BUFFER_SIZE];
  10. int in = 0, out = 0;
  11.  
  12. sem_t mutex, full, empty;
  13.  
  14. void *producer(void *arg) {
  15.     while (1) {
  16.         int item = rand() % 100;
  17.         sem_wait(&empty);
  18.         sem_wait(&mutex);
  19.  
  20.  
  21.         buffer[in] = item;
  22.         printf("Produced item: %d\n", item);
  23.         in = (in + 1) % BUFFER_SIZE;
  24.  
  25.         sem_post(&mutex);
  26.         sem_post(&full);
  27.  
  28.         sleep(1);
  29.     }
  30. }
  31.  
  32. void *consumer(void *arg) {
  33.     while (1) {
  34.         int item;
  35.         sem_wait(&full);
  36.         sem_wait(&mutex);
  37.  
  38.         item = buffer[out];
  39.         printf("Consumed item: %d\n", item);
  40.         out = (out + 1) % BUFFER_SIZE;
  41.  
  42.         sem_post(&mutex);
  43.         sem_post(&empty);
  44.  
  45.         sleep(2);
  46.     }
  47. }
  48.  
  49. int main() {
  50.     pthread_t prod_thread, cons_thread;
  51.  
  52.     sem_init(&mutex, 0, 1);
  53.     sem_init(&full, 0, 0);
  54.     sem_init(&empty, 0, BUFFER_SIZE);
  55.  
  56.     pthread_create(&prod_thread, NULL, producer, NULL);
  57.     pthread_create(&cons_thread, NULL, consumer, NULL);
  58.  
  59.     pthread_join(prod_thread, NULL);
  60.     pthread_join(cons_thread, NULL);
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement