-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader_writer.c
More file actions
70 lines (53 loc) · 939 Bytes
/
reader_writer.c
File metadata and controls
70 lines (53 loc) · 939 Bytes
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t mutex,writeblock;
int data = 0,rcount =0;
void *reader(void *arg)
{
int r;
r = ((int)arg);
sem_wait(&mutex);
rcount++;
if(rcount==1)
sem_wait(&writeblock);
printf("\n\t%d read by the reader:%d",data,r);
sem_post(&mutex);
sleep(1);
sem_wait(&mutex);
rcount--;
if(rcount==0)
sem_post(&writeblock);
sem_post(&mutex);
}
void *writer(void *arg)
{
int r;
r = ((int)arg);
sem_wait(&writeblock);
data++;
printf("\n%d written by the writer:%d",data,r);
sleep(2);
sem_post(&writeblock);
}
main()
{
int i,b;
while(1)
{
pthread_t rdid[5],wrid[5];
sem_init(&mutex,0,1);
sem_init(&writeblock,0,1);
for(i=0;i<3;i++)
{
pthread_create(&wrid[i],NULL,writer,(void *)i);
sleep(1);
pthread_create(&rdid[i],NULL,reader,(void *)i);
}
for(i=0;i<3;i++)
{
pthread_join(wrid[i],NULL);
pthread_join(rdid[i],NULL);
}
}
}