fork download
  1. #include<stdio.h>
  2. #include<semaphore.h>
  3. #include<pthread.h>
  4. #include<stdlib.h>
  5. #define buffersize 10
  6. pthread_mutex_t mutex;
  7. pthread_t tidP[20],tidC[20];
  8. sem_t full,empty;
  9. int counter;
  10. int buffer[buffersize];
  11.  
  12. void initialize()
  13. {
  14. pthread_mutex_init(&mutex,NULL);
  15. sem_init(&full,1,0);
  16. sem_init(&empty,1,buffersize);
  17. counter=0;
  18. }
  19.  
  20. void write(int item)
  21. {
  22. buffer[counter++]=item;
  23. }
  24.  
  25. int read()
  26. {
  27. return(buffer[--counter]);
  28. }
  29.  
  30. void * producer (void * param)
  31. {
  32. int waittime,item,i;
  33. item=rand()%5;
  34. waittime=rand()%5;
  35. sem_wait(&empty);
  36. pthread_mutex_lock(&mutex);
  37. printf("\nProducer has produced item: %d\n",item);
  38. write(item);
  39. pthread_mutex_unlock(&mutex);
  40. sem_post(&full);
  41. }
  42.  
  43. void * consumer (void * param)
  44. {
  45. int waittime,item;
  46. waittime=rand()%5;
  47. sem_wait(&full);
  48. pthread_mutex_lock(&mutex);
  49. item=read();
  50. printf("\nConsumer has consumed item: %d\n",item);
  51. pthread_mutex_unlock(&mutex);
  52. sem_post(&empty);
  53. }
  54.  
  55. int main()
  56. {
  57. int n1,n2,i;
  58. initialize();
  59. printf("\nEnter the no of producers: ");
  60. scanf("%d",&n1);
  61. printf("\nEnter the no of consumers: ");
  62. scanf("%d",&n2);
  63. for(i=0;i<n1;i++)
  64. pthread_create(&tidP[i],NULL,producer,NULL);
  65. for(i=0;i<n2;i++)
  66. pthread_create(&tidC[i],NULL,consumer,NULL);
  67. for(i=0;i<n1;i++)
  68. pthread_join(tidP[i],NULL);
  69. for(i=0;i<n2;i++)
  70. pthread_join(tidC[i],NULL);
  71.  
  72. //sleep(5);
  73. exit(0);
  74. }
Success #stdin #stdout 0.01s 5276KB
stdin
4
3
stdout
Enter the no of producers: 
Enter the no of consumers: 
Producer has produced item: 0

Consumer has consumed item: 0

Producer has produced item: 0

Consumer has consumed item: 0

Producer has produced item: 2

Consumer has consumed item: 2

Producer has produced item: 1