Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <sys/eventfd.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <time.h>
  7. #include <errno.h>
  8.  
  9. #define MAX_THREADS 2
  10.  
  11. int val ;
  12. int ok2consume, ok2produce ;
  13. void *bufr ;
  14. int bufw = 1 ;
  15.  
  16. void *producer(void *arg){
  17. while(1){
  18. int wtime = (random() % 10) + 1;
  19. read(ok2produce,bufr,sizeof(uint64_t));
  20. val = (random() % 255) + 1 ;
  21. printf("%d\n",val);
  22. write(ok2consume,&bufw,sizeof(uint64_t));
  23. sleep(wtime);
  24.  
  25. }
  26.  
  27. }
  28.  
  29. void *consumer(void *arg){
  30. while(1){
  31. int wtime = (random() % 10) + 1 ;
  32. read(ok2consume,bufr,sizeof(uint64_t));
  33. printf("%d\n",val);
  34. write(ok2produce,&bufw,sizeof(uint64_t));
  35. sleep(wtime);
  36. }
  37. }
  38.  
  39. int main(void){
  40. pthread_t TID[MAX_THREADS] ;
  41. int retval[MAX_THREADS];
  42.  
  43. ok2produce = eventfd(1,EFD_SEMAPHORE);
  44. ok2consume = eventfd(0,EFD_SEMAPHORE);
  45.  
  46. pthread_create(&TID[1], NULL, consumer,&val);
  47. pthread_create(&TID[0], NULL, producer,&val);
  48. printf("Producer ID = %ld created!\n",TID[0] ) ;
  49.  
  50. printf("Consumer ID = %ld created!\n",TID[1] ) ;
  51.  
  52. pthread_join(TID[0],(void*)&retval[0]);
  53. printf("Thread %ld terminated\n",TID[0]);
  54. pthread_join(TID[1],(void*)&retval[1]);
  55. printf("Thread %ld terminated\n",TID[1]);
  56.  
  57. close(ok2consume);
  58. close(ok2produce);
  59.  
  60. return 0 ;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement