forked from remzi-arpacidusseau/ostep-homework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader-writer.c
86 lines (64 loc) · 1.5 KB
/
reader-writer.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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "common_threads.h"
//
// Your code goes in the structure and functions below
//
typedef struct __rwlock_t {
} rwlock_t;
void rwlock_init(rwlock_t *rw) {
}
void rwlock_acquire_readlock(rwlock_t *rw) {
}
void rwlock_release_readlock(rwlock_t *rw) {
}
void rwlock_acquire_writelock(rwlock_t *rw) {
}
void rwlock_release_writelock(rwlock_t *rw) {
}
//
// Don't change the code below (just use it!)
//
int loops;
int value = 0;
rwlock_t lock;
void *reader(void *arg) {
int i;
for (i = 0; i < loops; i++) {
rwlock_acquire_readlock(&lock);
printf("read %d\n", value);
rwlock_release_readlock(&lock);
}
return NULL;
}
void *writer(void *arg) {
int i;
for (i = 0; i < loops; i++) {
rwlock_acquire_writelock(&lock);
value++;
printf("write %d\n", value);
rwlock_release_writelock(&lock);
}
return NULL;
}
int main(int argc, char *argv[]) {
assert(argc == 4);
int num_readers = atoi(argv[1]);
int num_writers = atoi(argv[2]);
loops = atoi(argv[3]);
pthread_t pr[num_readers], pw[num_writers];
rwlock_init(&lock);
printf("begin\n");
int i;
for (i = 0; i < num_readers; i++)
Pthread_create(&pr[i], NULL, reader, NULL);
for (i = 0; i < num_writers; i++)
Pthread_create(&pw[i], NULL, writer, NULL);
for (i = 0; i < num_readers; i++)
Pthread_join(pr[i], NULL);
for (i = 0; i < num_writers; i++)
Pthread_join(pw[i], NULL);
printf("end: value %d\n", value);
return 0;
}