fork download
  1. #include<stdio.h>
  2. #include<pthread.h>
  3. #include<semaphore.h>
  4.  
  5. sem_t mutex,writeblock;
  6. int data = 0,rcount = 0;
  7.  
  8. void *reader(void *arg)
  9. {
  10. int f;
  11. f = ((int)arg);
  12. sem_wait(&mutex);
  13. rcount = rcount + 1;
  14. if(rcount==1)
  15. sem_wait(&writeblock);
  16. sem_post(&mutex);
  17. printf("Data read by the reader%d is %d\n",f,data);
  18. sleep(1);
  19. sem_wait(&mutex);
  20. rcount = rcount - 1;
  21. if(rcount==0)
  22. sem_post(&writeblock);
  23. sem_post(&mutex);
  24. }
  25.  
  26. void *writer(void *arg)
  27. {
  28. int f;
  29. f = ((int) arg);
  30. sem_wait(&writeblock);
  31. data++;
  32. printf("Data writen by the writer%d is %d\n",f,data);
  33. sleep(1);
  34. sem_post(&writeblock);
  35. }
  36.  
  37. int main()
  38. {
  39. int i,b;
  40. pthread_t rtid[5],wtid[5];
  41. sem_init(&mutex,0,1);
  42. sem_init(&writeblock,0,1);
  43. for(i=0;i<=2;i++)
  44. {
  45. pthread_create(&wtid[i],NULL,writer,(void *)i);
  46. pthread_create(&rtid[i],NULL,reader,(void *)i);
  47. }
  48. for(i=0;i<=2;i++)
  49. {
  50. pthread_join(wtid[i],NULL);
  51. pthread_join(rtid[i],NULL);
  52. }
  53. return 0;
  54. }
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
Data read by the reader2 is 0
Data read by the reader1 is 0
Data read by the reader0 is 0
Data writen by the writer2 is 1
Data writen by the writer1 is 2
Data writen by the writer0 is 3