0% found this document useful (0 votes)
34 views3 pages

Operating System 8

The document contains code implementing the readers-writers problem using semaphores in C. It defines two semaphores - mutex and writeblock. There are reader and writer threads that access a shared data variable in a synchronized manner using these semaphores. Main creates 5 reader and 5 writer threads and joins them after they complete their tasks.

Uploaded by

saurabh tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views3 pages

Operating System 8

The document contains code implementing the readers-writers problem using semaphores in C. It defines two semaphores - mutex and writeblock. There are reader and writer threads that access a shared data variable in a synchronized manner using these semaphores. Main creates 5 reader and 5 writer threads and joins them after they complete their tasks.

Uploaded by

saurabh tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Name: Devesh Vikram Singh

Roll: 2100290110050
Lab: Operating System
Batch: A2

Ques:1 Implement the solution of Readers


Writers problem Using Semaphore?
Code:
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>

sem_t mutex,writeblock;
int data = 0,rcount = 0;

void *reader(void *arg)


{
int f;
f = ((int)arg);
sem_wait(&mutex);
rcount = rcount + 1;
if(rcount==1)
sem_wait(&writeblock);
sem_post(&mutex);
printf("Data read by the reader%d is
%d\n",f,data);
sleep(1);
sem_wait(&mutex);
rcount = rcount - 1;
if(rcount==0)
sem_post(&writeblock);
sem_post(&mutex);
}

void *writer(void *arg)


{
int f;
f = ((int) arg);
sem_wait(&writeblock);
data++;
printf("Data writen by the writer%d is
%d\n",f,data);
sleep(1);
sem_post(&writeblock);
}

int main()
{
int i,b;
pthread_t rtid[5],wtid[5];
sem_init(&mutex,0,1);
sem_init(&writeblock,0,1);
for(i=0;i<=2;i++)
{
pthread_create(&wtid[i],NULL,writer,(void
*)i);
pthread_create(&rtid[i],NULL,reader,(void
*)i);
}
for(i=0;i<=2;i++)
{
pthread_join(wtid[i],NULL);
pthread_join(rtid[i],NULL);
}
return 0;
}

Output:

You might also like