Advertisement
100rads

uvjetna varijabla / OS

Apr 13th, 2019
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.95 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4.  
  5. pthread_mutex_t mutex;
  6. pthread_cond_t full;
  7.  
  8. char buffer[10];
  9.  
  10. void *Producer() {
  11.     int i;
  12.     pthread_mutex_lock(&mutex);
  13.  
  14.     for(i = 0; i <= 10; i++){
  15.  
  16.         buffer[i] = i;
  17.         printf("Produced: %d\n", buffer[i]);
  18.         if(i==10) {
  19.             pthread_cond_signal(&full);
  20.             printf("Signal sent\n");
  21.         }
  22.         sleep(1);
  23.     }
  24.  
  25.     pthread_mutex_unlock(&mutex);
  26.  
  27.     pthread_exit(NULL);
  28. }
  29.  
  30. void *Consumer() {
  31.     int j;
  32.     pthread_mutex_lock(&mutex);
  33.  
  34.     for(j = 0; j <= 10; j++) {
  35.         j = buffer[j];
  36.         printf("Consumed: %d\n", buffer[j]);
  37.         sleep(1);
  38.     }
  39.    
  40.     pthread_cond_wait(&full,&mutex);
  41.     pthread_mutex_unlock(&mutex);
  42.  
  43.     pthread_exit(NULL);
  44. }
  45.  
  46. int main() {
  47.     pthread_t t1, t2;
  48.     void *t;
  49.  
  50.     pthread_create(&t1, NULL, Producer, NULL);
  51.     pthread_create(&t2, NULL, Consumer, NULL);
  52.     pthread_join(t1, &t);
  53.     printf("Producer finished.\n");
  54.     pthread_join(t2, &t);
  55.     printf("Consumer finished. \n");
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement