-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrwlock_fair.c
More file actions
129 lines (118 loc) · 2.68 KB
/
Copy pathrwlock_fair.c
File metadata and controls
129 lines (118 loc) · 2.68 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct {
pthread_mutex_t m;
pthread_cond_t readers_ok;
pthread_cond_t writers_ok;
int readers;
int writers;
int writers_waiting;
} rwlock_t;
static void rwlock_init(rwlock_t *l)
{
pthread_mutex_init(&l->m, NULL);
pthread_cond_init(&l->readers_ok, NULL);
pthread_cond_init(&l->writers_ok, NULL);
l->readers = 0;
l->writers = 0;
l->writers_waiting = 0;
}
static void rwlock_rdlock(rwlock_t *l)
{
pthread_mutex_lock(&l->m);
while (l->writers || l->writers_waiting) {
pthread_cond_wait(&l->readers_ok, &l->m);
}
l->readers++;
pthread_mutex_unlock(&l->m);
}
static void rwlock_rdunlock(rwlock_t *l)
{
pthread_mutex_lock(&l->m);
l->readers--;
if (l->readers == 0 && l->writers_waiting) {
pthread_cond_signal(&l->writers_ok);
}
pthread_mutex_unlock(&l->m);
}
static void rwlock_wrlock(rwlock_t *l)
{
pthread_mutex_lock(&l->m);
l->writers_waiting++;
while (l->writers || l->readers) {
pthread_cond_wait(&l->writers_ok, &l->m);
}
l->writers_waiting--;
l->writers = 1;
pthread_mutex_unlock(&l->m);
}
static void rwlock_wrunlock(rwlock_t *l)
{
pthread_mutex_lock(&l->m);
l->writers = 0;
if (l->writers_waiting) {
pthread_cond_signal(&l->writers_ok);
} else {
pthread_cond_broadcast(&l->readers_ok);
}
pthread_mutex_unlock(&l->m);
}
typedef struct {
rwlock_t *l;
int id;
} rarg_t;
static int shared_value = 0;
static void *reader(void *p)
{
rarg_t *a = p;
for (int i = 0; i < 20; i++) {
rwlock_rdlock(a->l);
int v = shared_value;
printf("R%d sees %d\n", a->id, v);
rwlock_rdunlock(a->l);
usleep(50000);
}
return NULL;
}
static void *writer(void *p)
{
rarg_t *a = p;
for (int i = 0; i < 10; i++) {
rwlock_wrlock(a->l);
shared_value++;
printf("W%d set %d\n", a->id, shared_value);
rwlock_wrunlock(a->l);
usleep(120000);
}
return NULL;
}
int main(void)
{
rwlock_t l;
rwlock_init(&l);
pthread_t r[3];
pthread_t w[2];
rarg_t ar[3];
rarg_t aw[2];
for (int i = 0; i < 3; i++) {
ar[i].l = &l;
ar[i].id = i;
pthread_create(&r[i], NULL, reader, &ar[i]);
}
for (int i = 0; i < 2; i++) {
aw[i].l = &l;
aw[i].id = i;
pthread_create(&w[i], NULL, writer, &aw[i]);
}
for (int i = 0; i < 3; i++) {
pthread_join(r[i], NULL);
}
for (int i = 0; i < 2; i++) {
pthread_join(w[i], NULL);
}
return 0;
}