-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprg5.c
49 lines (49 loc) · 1006 Bytes
/
prg5.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#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 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 written by writer %d is %d \n",f,data);
sleep(1);
sem_post(&writeblock);
}
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);
}
}