Advertisement
Guest User

syf

a guest
Apr 10th, 2020
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.00 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <string.h>
  6. #include <errno.h>
  7. #include <fcntl.h>
  8. #include <semaphore.h>
  9.  
  10. pthread_mutex_t prod_mutex, cons_mutex;
  11. pthread_cond_t ready_to_produce =PTHREAD_COND_INITIALIZER;
  12.  
  13. pthread_cond_t ready_to_consume =PTHREAD_COND_INITIALIZER;
  14. #define MAX 5
  15.  
  16. int buf[MAX];
  17. int pid;
  18.  
  19. void* prod(void *p){
  20.    int index = 0;
  21.    int i;
  22.    pthread_mutex_lock(&prod_mutex);
  23.    for (i=0;i<100;i++){
  24.       buf[index] = i;
  25.       if (index == 0 && i >= 5)
  26.       {
  27.       pthread_cond_wait(&ready_to_produce, &prod_mutex);
  28.       }
  29.       index = (index + 1) % MAX;
  30.      
  31.       pthread_mutex_unlock(&prod_mutex);
  32.       if (index == 0)
  33.       {
  34.       pthread_mutex_lock(&cons_mutex);
  35.       pthread_cond_signal(&ready_to_consume);
  36.       pthread_mutex_unlock(&cons_mutex);
  37.       }
  38.      
  39.    }
  40. }
  41. void* kons(void *p){
  42.    int index = 0;
  43.    int i;
  44.    
  45.    for (i=0;i<100;i++){
  46.             if (index == 0 && i >= 5)
  47.       {
  48.       pthread_cond_wait(&ready_to_consume, &cons_mutex);
  49.       }
  50.       printf("Process %d : %d\n", pid,  buf[index]);
  51.       index = (index + 1) % MAX;
  52.       pthread_mutex_unlock(&cons_mutex);
  53.       if ( index == 0)
  54.       {
  55.       pthread_mutex_lock(&prod_mutex);
  56.       pthread_cond_signal(&ready_to_produce);
  57.       pthread_mutex_unlock(&prod_mutex);
  58.        
  59.       }
  60.      
  61.    }
  62. }
  63.  
  64. int main(){
  65.    
  66.    pthread_mutex_init(&prod_mutex, NULL);
  67.    pthread_mutex_init(&cons_mutex, NULL);
  68.  
  69.  
  70.    pthread_t pth1, pth2, pth3, pth4;
  71.    pthread_create(&pth1, NULL, prod, NULL);
  72.    pthread_create(&pth2, NULL, prod, NULL);
  73.    pthread_create(&pth3, NULL, kons, NULL);
  74.    pthread_create(&pth4, NULL, kons, NULL);
  75.    pthread_join(pth1, NULL);
  76.    pthread_join(pth2, NULL);
  77.    pthread_join(pth3, NULL);
  78.    pthread_join(pth4, NULL);
  79.  
  80.      
  81.    pthread_mutex_destroy(&prod_mutex);
  82.    pthread_mutex_destroy(&cons_mutex);
  83.    pthread_cond_destroy(&ready_to_consume);
  84.    pthread_cond_destroy(&ready_to_produce);
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement