Advertisement
_Black_Panther_

Untitled

Mar 19th, 2021
762
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.15 KB | None | 0 0
  1. // gcc rw.c -pthread
  2. // a.out
  3.  
  4. #include<stdio.h>
  5. #include<pthread.h>
  6. #include<semaphore.h>
  7.  
  8. sem_t mutex;
  9. sem_t db;
  10. int readercount=0;
  11. pthread_t reader1,reader2,writer1,writer2;
  12. void *reader(void *);
  13. void *writer(void *);
  14. main()
  15. {
  16.     sem_init(&mutex,0,1);
  17.     sem_init(&db,0,1);
  18.     while(1)
  19.     {
  20.         pthread_create(&reader1,NULL,reader,"1");
  21.         pthread_create(&reader2,NULL,reader,"2");
  22.         pthread_create(&writer1,NULL,writer,"1");
  23.         pthread_create(&writer2,NULL,writer,"2");
  24.     }
  25. }
  26. void *reader(void *p)
  27. {
  28.     printf("prevoius value %d\n",mutex);
  29.     sem_wait(&mutex);
  30.     printf("Mutex acquired by reader %d\n",mutex);
  31.     readercount++;
  32.     if(readercount==1) sem_wait(&db);
  33.     sem_post(&mutex);
  34.     printf("Mutex returned by reader %d\n",mutex);
  35.     printf("Reader %s is Reading\n",p);
  36. sleep(3);
  37.     sem_wait(&mutex);
  38.     printf("Reader %s Completed Reading\n",p);
  39.     readercount--;
  40.     if(readercount==0) sem_post(&db);
  41.     sem_post(&mutex);
  42. }
  43.  
  44. void *writer(void *p)
  45. {
  46.     printf("Writer is Waiting \n");
  47.     sem_wait(&db);
  48.     printf("Writer %s is writing\n",p);
  49.     sem_post(&db);
  50. sleep(2);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement