Assignment No.
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.
Name:Rasal Aarya Vijay Batch : B Roll No : 23107101
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;
void *writer(void *arg) { while
(running) { sem_wait(&w);
printf("writer is writing....\n");
sleep(1); printf("writer finished
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");
sleep(1); printf("reader finished
reading...\n");
pthread_mutex_lock(&m);
Rc--; if (Rc
== 0)
{ sem_post(&w
);
pthread_mutex_unlock(&m);
sleep(2);
return NULL;
int main()
{ pthread_t r1, r2,
w1;
sem_init(&w, 0, 1);
pthread_mutex_init(&m, NULL);
pthread_create(&r1, NULL, reader,
NULL); pthread_create(&r2, NULL,
reader, NULL); pthread_create(&w1,
NULL, writer, NULL);
printf("Press ENTER to stop...\n");
getchar(); running = false;
pthread_join(r1, NULL);
pthread_join(r2, NULL);
pthread_join(w1, NULL);
sem_destroy(&w);
pthread_mutex_destroy(&m);
return 0;
Output :
Press ENTER to stop...
reader is reading...
reader is reading...
reader finished reading...
reader finished reading...
writer is writing....
writer finished writing..
reader is reading...
reader is reading...