-
Notifications
You must be signed in to change notification settings - Fork 0
/
readerwriter.c
61 lines (40 loc) · 904 Bytes
/
readerwriter.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
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
int rcounter = 0;
pthread_mutex_t mutex, wrt;
pthread_t w, r;
void * reader(void * params)
{
pthread_mutex_lock(&mutex);
rcounter++;
if(rcounter == 1)
pthread_mutex_lock(&wrt);
pthread_mutex_unlock(&mutex);
printf("Reading %d Reading\n", rcounter);
pthread_mutex_lock(&mutex);
rcounter--;
if(rcounter == 0)
pthread_mutex_unlock(&wrt);
pthread_mutex_unlock(&mutex);
}
void * writer(void * params)
{
pthread_mutex_lock(&wrt);
printf("Writer Writes\n");
pthread_mutex_unlock(&wrt);
}
int main()
{
pthread_mutex_init(&mutex, NULL);
pthread_mutex_init(&wrt, NULL);
pthread_create(&r, NULL, reader, NULL);
pthread_create(&r, NULL, reader, NULL);
pthread_create(&w, NULL, writer, NULL);
pthread_join(r, NULL);
pthread_join(r, NULL);
pthread_join(w, NULL);
printf("\n");
return 0;
}