Os Assign4
Os Assign4
04
Title : Write a program using semaphores to implement the Readers-Writers problem,
ensuring mutual exclusion while allowing multiple readers and one writer to access a
shared resource concurrently.
Program :
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdbool.h>
sem_t w;
pthread_mutex_t
m; int Rc = 0; bool
running = true;
(running) { sem_wait(&w);
printf("writer is writing....\n");
writing..\n"); sem_post(&w);
sleep(2);
return NULL;
}
void *reader(void *arg)
{ while (running)
{ pthread_mutex_lock(&m
); Rc++; if (Rc == 1) {
sem_wait(&w);
pthread_mutex_unlock(&m);
printf("reader is reading...\n");
reading...\n");
pthread_mutex_lock(&m);
Rc--; if (Rc
== 0)
{ sem_post(&w
);
pthread_mutex_unlock(&m);
sleep(2);
return NULL;
int main()
w1;
sem_init(&w, 0, 1);
pthread_mutex_init(&m, NULL);
pthread_join(r1, NULL);
pthread_join(r2, NULL);
pthread_join(w1, NULL);
sem_destroy(&w);
pthread_mutex_destroy(&m);
return 0;
Output :
reader is reading...
reader is reading...
reader is reading...
reader is reading...