-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathrwlock.c
99 lines (83 loc) · 1.92 KB
/
rwlock.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
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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include "common.h"
#include "common_threads.h"
#ifdef linux
#include <semaphore.h>
#elif __APPLE__
#include "zemaphore.h"
#endif
typedef struct _rwlock_t {
sem_t writelock;
sem_t lock;
int readers;
} rwlock_t;
void rwlock_init(rwlock_t *lock) {
lock->readers = 0;
Sem_init(&lock->lock, 1);
Sem_init(&lock->writelock, 1);
}
void rwlock_acquire_readlock(rwlock_t *lock) {
Sem_wait(&lock->lock);
lock->readers++;
if (lock->readers == 1)
Sem_wait(&lock->writelock);
Sem_post(&lock->lock);
}
void rwlock_release_readlock(rwlock_t *lock) {
Sem_wait(&lock->lock);
lock->readers--;
if (lock->readers == 0)
Sem_post(&lock->writelock);
Sem_post(&lock->lock);
}
void rwlock_acquire_writelock(rwlock_t *lock) {
Sem_wait(&lock->writelock);
}
void rwlock_release_writelock(rwlock_t *lock) {
Sem_post(&lock->writelock);
}
int read_loops;
int write_loops;
int counter = 0;
rwlock_t mutex;
void *reader(void *arg) {
int i;
int local = 0;
for (i = 0; i < read_loops; i++) {
rwlock_acquire_readlock(&mutex);
local = counter;
rwlock_release_readlock(&mutex);
printf("read %d\n", local);
}
printf("read done: %d\n", local);
return NULL;
}
void *writer(void *arg) {
int i;
for (i = 0; i < write_loops; i++) {
rwlock_acquire_writelock(&mutex);
counter++;
rwlock_release_writelock(&mutex);
}
printf("write done\n");
return NULL;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "usage: rwlock readloops writeloops\n");
exit(1);
}
read_loops = atoi(argv[1]);
write_loops = atoi(argv[2]);
rwlock_init(&mutex);
pthread_t c1, c2;
Pthread_create(&c1, NULL, reader, NULL);
Pthread_create(&c2, NULL, writer, NULL);
Pthread_join(c1, NULL);
Pthread_join(c2, NULL);
printf("all done\n");
return 0;
}