Advertisement
Guest User

Untitled

a guest
Jan 16th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.09 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<pthread.h>
  3. #include<semaphore.h>
  4. #include<stdlib.h>
  5. #include<time.h>
  6.  
  7.  
  8. #define N 5
  9. struct buffer
  10. {
  11.     int b[N];//bufferi
  12.     sem_t empty,full;
  13.     int in,out;
  14. } buf;// emri gjeneral i struktures shiko tek sem_wait qyshj e kemi perdor
  15.  
  16. void *P()
  17. {  
  18.     time_t seconds;
  19.     seconds=time(NULL);
  20.     int i=1;
  21.     while(1)
  22.     {
  23.         sem_wait(&(buf.empty));
  24.         buf.b[buf.in]=i;
  25.         buf.in = (buf.in+1)%N;
  26.         printf("\nProdhuesi:%d \t --- [%d]",i++,seconds/3600);
  27.         sleep(1);
  28.         sem_post(&(buf.full));
  29.     }  
  30. }
  31.  
  32. void *C()
  33. {
  34.     int item;
  35.     while(1)
  36.     {
  37.         sem_wait(&(buf.full));
  38.         item = buf.b[buf.out];
  39.         buf.out = (buf.out+1)%N;
  40.         printf("\tKonsumuesi:%d ",item);
  41.         sem_post(&(buf.empty));
  42.     }  
  43. }
  44.  
  45. void main()
  46. {
  47.     pthread_t t1,t2;//t1 si prodhues,t2 si konsumues dmth threda per qito dyja
  48.    
  49.     sem_init(&(buf.empty),0,N);//0 dmth po pajtohet mu bo shared
  50.     sem_init(&(buf.full),0,0);
  51.    
  52.     buf.in=0;
  53.     buf.out=0;
  54.    
  55.     pthread_create(&t2,NULL,C,NULL);
  56.     pthread_create(&t1,NULL,P,NULL);//qiky thread po kriojet per prodhuesin
  57.    
  58.  
  59.     pthread_join(t1,NULL);
  60.     pthread_join(t2,NULL);
  61.  
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement