-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12b.c
54 lines (46 loc) · 1.12 KB
/
12b.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
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
sem_t wrt;
pthread_mutex_t mutex;
int cnt = 1;
int numreader = 0;
void *writer(void *wno) {
sem_wait(&wrt);
cnt = cnt * 2;
printf("Writer %d modified cnt to %d\n", (*((int *)wno)), cnt);
sem_post(&wrt);
}
void *reader(void *rno) {
pthread_mutex_lock(&mutex);
numreader++;
if (numreader == 1)
sem_wait(&wrt);
pthread_mutex_unlock(&mutex);
printf("Reader %d: read cnt as %d\n", *((int *)rno), cnt);
pthread_mutex_lock(&mutex);
numreader--;
if (numreader == 0) {
sem_post(&wrt);
}
pthread_mutex_unlock(&mutex);
}
int main() {
pthread_t read[10], write[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt, 0, 1);
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < 10; i++) {
pthread_create(&read[i], NULL, (void *)reader, (void *)&a[i]);
}
for (int i = 0; i < 5; i++) {
pthread_create(&write[i], NULL, (void *)writer, (void *)&a[i]);
}
for (int i = 0; i < 5; i++) {
pthread_join(read[i], NULL);
pthread_join(write[i], NULL);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);
return 0;
}