fork download
  1. #include <pthread.h>
  2. //#include<semaphore.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <windows.h>
  6.  
  7. pthread_mutex_t x,wsem;
  8. int readcount;
  9. int data;
  10.  
  11. void intialize()
  12. {
  13. pthread_mutex_init(&x,NULL);
  14. pthread_mutex_init(&wsem,NULL);
  15. readcount=0;
  16. data=0;
  17. }
  18.  
  19. void * reader (void * param)
  20. {
  21. int waittime;
  22.  
  23. //printf("\nReader id= %lu is trying to enter",pthread_self());
  24. pthread_mutex_lock(&x);
  25. readcount++;
  26. if(readcount==1){
  27. pthread_mutex_lock(&wsem);}
  28. printf("\nReader id= %lu has entered",pthread_self());
  29. printf("\n%d Reader is inside ",readcount);
  30. pthread_mutex_unlock(&x);
  31. waittime = ((rand()%5+1))*1000;
  32. printf("\n Reader sleep: %d s ",(waittime/1000));
  33. printf("\n Reader data: %d ",data);
  34. Sleep(waittime);
  35. printf("\nReader id= %lu is Leaving",pthread_self());
  36. pthread_mutex_lock(&x);
  37. readcount--;
  38. if(readcount==0){
  39. //printf("\nReader id= %lu is Leaving",pthread_self());
  40. pthread_mutex_unlock(&wsem);
  41. //printf("\nReader id= %lu is Leaving",pthread_self());
  42. }
  43. //printf("\nReader id= %lu is Leaving",pthread_self());
  44. pthread_mutex_unlock(&x);
  45. //printf("\nReader id= %lu is Leaving",pthread_self());
  46. pthread_exit(NULL);
  47. }
  48.  
  49. void * writer (void * param)
  50. {
  51. int waittime;
  52.  
  53. //printf("\nWriter id= %lu is trying to enter",pthread_self());
  54. pthread_mutex_lock(&wsem);
  55. printf("\nWrite id= %lu has entered",pthread_self());
  56. waittime=((rand()%3)+1)*1000;
  57. printf("\n Writer sleep: %d s ",(waittime/1000));
  58. data = rand()%50;
  59. printf("\n Writer update data: %d ",data);
  60. Sleep(waittime);
  61. printf("\nWriter id= %lu is leaving",pthread_self());
  62. pthread_mutex_unlock(&wsem);
  63. //printf("\nWriter id= %lu is leaving",pthread_self());
  64. //Sleep(30);
  65. pthread_exit(NULL);
  66. //exit(0);
  67. }
  68.  
  69. int main()
  70. {
  71. int n1,n2,i;
  72. printf("\nEnter the no of writers: ");
  73. scanf("%d",&n1);
  74. printf("\nEnter the no of readers: ");
  75. scanf("%d",&n2);
  76. intialize();
  77. pthread_t writerThreads[n1],readThreads[n2];
  78. for(i=0;i<n1;i++){
  79. pthread_create(&writerThreads[i],NULL,writer,NULL);}
  80. for(i=0;i<n2;i++){
  81. pthread_create(&readThreads[i],NULL,reader,NULL);}
  82. for(i=0;i<n1;i++){
  83. pthread_join(writerThreads[i],NULL);}
  84. for(i=0;i<n2;i++){
  85. pthread_join(readThreads[i],NULL);}
  86. //Sleep(30);
  87. exit(0);
  88. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.c:5:21: fatal error: windows.h: No such file or directory
 #include <windows.h>
                     ^
compilation terminated.
stdout
Standard output is empty