/* readerWriter1.c++ Reader priority, starvation of writer $ g++ -Wall readerWriter1.c++ -lpthread */ #include using namespace std; #include #include #include #include #include #include #include #include #include #include #include #define SIZE 16 int main(){ int shmID, *readerCountP, *dP, status, val ; pid_t rpid1, rpid2, wpid1, wpid2; struct shmid_ds buff; sem_t *mutexP, *countsemP; // shared memory shmID = shmget(ftok("/home/goutam", 1234), SIZE, IPC_CREAT | 0777); if(shmID == -1) { cerr << "Error in shmget"; exit(1) ; } readerCountP = (int *)shmat(shmID, 0, 0777); *readerCountP = 0; dP = readerCountP + 1; *dP = 0; // semaphore mutexP = sem_open("/abcd", O_CREAT, 0777, 1); if(mutexP == SEM_FAILED && errno != EEXIST){ cerr << errno << " Semaphore error\n"; exit(1); } countsemP = sem_open("/efgh", O_CREAT, 0777, 1); if(countsemP == SEM_FAILED && errno != EEXIST){ cerr << errno << " Semaphore error\n"; exit(1); } sem_getvalue(mutexP, &val); if(val==0) sem_post(mutexP); sem_getvalue(countsemP, &val); if(val==0) sem_post(countsemP); wpid1 = fork(); if(wpid1 == -1){ perror("First fork fails\n"); exit(1); } if(wpid1 > 0){ wpid2 = fork(); if(wpid2 == -1){ perror("Second fork fails\n"); exit(1); } if(wpid2 > 0) { rpid1 = fork(); if(rpid1 == -1){ perror("Third fork fails\n"); exit(1); } if(rpid1 > 0) { rpid2 = fork(); if(rpid2 == -1){ perror("Fourth fork fails\n"); exit(1); } if(rpid2 > 0) { // parent waitpid(wpid1, &status, 0); waitpid(wpid2, &status, 0); waitpid(rpid1, &status, 0); waitpid(rpid2, &status, 0); shmdt(readerCountP); shmctl(shmID, IPC_RMID, &buff); sem_close(mutexP); sem_close(countsemP); } else { // child: reader 2 int i; for(i=0; i<=1000; ++i){ sem_wait(countsemP); ++(*readerCountP); if(*readerCountP == 1) sem_wait(mutexP); sem_post(countsemP); cout << "reader 2: " << *dP << endl; sleep(1); sem_wait(countsemP); --(*readerCountP); if(*readerCountP == 0) sem_post(mutexP); sem_post(countsemP); // sleep(1); } } } else { // child: reader 1 int i; for(i=0; i<=1000; ++i){ sem_wait(countsemP); ++(*readerCountP); if(*readerCountP == 1) sem_wait(mutexP); sem_post(countsemP); cout << "reader 1: " << *dP << endl; sleep(1); sem_wait(countsemP); --(*readerCountP); if(*readerCountP == 0) sem_post(mutexP); sem_post(countsemP); // sleep(1); } } } else { // child: writer 2 int i; for(i=0; i<=1000; ++i){ sem_wait(mutexP); ++(*dP); cout << "---> writer 2: " << *dP << endl; // sleep(1); sem_post(mutexP); sleep(1); } } } else { // child: writer 1 int i; for(i=0; i<=1000; ++i){ sem_wait(mutexP); ++(*dP); cout << "---> writer 1: " << *dP << endl; // sleep(1); sem_post(mutexP); sleep(1); } } return 0; }