sema_rw.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include<cstdio>
  2. #include<iostream>
  3. #include<cstdlib>
  4. #include<pthread.h>
  5. #include<semaphore.h>
  6. #include<unistd.h>
  7. using namespace std;
  8. sem_t rmutex,wmutex,lockmutex;
  9. int rc;
  10. void*reader_p(void*id)
  11. {
  12. int i=(long)id;
  13. sem_wait(&rmutex);
  14. rc++;
  15. printf("reader %d entered library\n",i);
  16. if(rc==1)
  17. {
  18. printf("reader locks the library\n");
  19. sem_wait(&lockmutex);
  20. }
  21. sem_post(&rmutex);
  22. sem_wait(&rmutex);
  23. rc--;
  24. printf("reader %d leaves library\n",i);
  25. if(rc==0)
  26. {
  27. printf("reader unlocks the library\n");
  28. sem_post(&lockmutex);
  29. }
  30. sem_post(&rmutex);
  31. }
  32. void*writer_p(void*id)
  33. {
  34. sem_wait(&lockmutex);
  35. printf("writer enters into library\n");
  36. printf("writer doing stuff\n");
  37. sem_post(&lockmutex);
  38. printf("writer leaves and unlocks the library\n");
  39. }
  40. int main()
  41. {
  42. pthread_t reader[3],writer;
  43. int j=1;
  44. for(int i=0;i<3;i++)
  45. pthread_create(&reader[i],NULL,reader_p,(void*)&i);
  46. pthread_create(&writer,NULL,writer_p,(void*)&j);
  47. sem_init(&rmutex,1,3);
  48. sem_init(&wmutex,1,0);
  49. sem_init(&lockmutex,1,1);
  50. for(int i=0;i<3;i++)
  51. pthread_join(reader[i],NULL);
  52. pthread_join(writer,NULL);
  53. return 0;
  54. }