Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<pthread.h>
  3. #include<semaphore.h>
  4. #include<unistd.h>
  5.  
  6. sem_t mutex;
  7. int buffer[5];
  8. int size=-1;
  9.  
  10. void *produce(void *arg){
  11. int count = 0;
  12. while(count<3){
  13. int i = (int)arg;
  14. sem_wait(&mutex);
  15. if(size!=4){
  16. buffer[++size] = rand()%10;
  17. printf("Producer %d produced %d\n", i, buffer[size]);
  18. count++;
  19. }
  20. else{
  21. printf("Buffer is full\n");
  22. }
  23. sem_post(&mutex);
  24. }
  25. }
  26.  
  27. void *consume(void *arg){
  28. int count = 0;
  29. while(count<3){
  30. int i = (int)arg;
  31. sem_wait(&mutex);
  32. if(size!=-1){
  33. printf("Consumer %d consumed %d\n", i, buffer[size--]);
  34. count++;
  35. }
  36. else{
  37. printf("Buffer is empty\n");
  38. }
  39. sem_post(&mutex);
  40. }
  41. }
  42.  
  43. void main(){
  44.  
  45. pthread_t producer[3] ,consumer[3];
  46. int i;
  47. sem_init(&mutex, 0, 1);
  48. printf("Starting\n");
  49. for(i=0; i<3; i++){
  50. pthread_create(&producer[i], NULL, produce, (void*)i);
  51. printf("1");
  52. pthread_create(&consumer[i], NULL, consume, (void*)i);
  53. printf("2");
  54. }
  55. for(i=0; i<3; i++){
  56. pthread_join(producer[i], NULL);
  57. pthread_join(consumer[i], NULL);
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement