forked from Lowkee1g/DockerContainerForC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReaderWriter.c
More file actions
70 lines (55 loc) · 1.38 KB
/
Copy pathReaderWriter.c
File metadata and controls
70 lines (55 loc) · 1.38 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
// Read læser count og writer prøver at adde 1 til counter writer på ikke skrive men en reader læser
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int counter = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int reader = 0;
void *readerfunc(void* arg) {
pthread_mutex_lock(&lock);
reader++;
printf("%d\n", counter);
reader--;
if(reader == 0){
pthread_cond_broadcast(&cond);
}
pthread_mutex_unlock(&lock);
pthread_exit(NULL);
}
void *writerfunc(void* arg) {
pthread_mutex_lock(&lock);
if (reader > 0)
{
while (reader != 0) {
pthread_cond_wait(&cond, &lock);
}
}
counter++;
printf("Writer +1\n");
pthread_mutex_unlock(&lock);
pthread_exit(NULL);
}
int main(){
pthread_t r1;
pthread_t r2;
pthread_t w;
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
while(1)
{
pthread_create(&w, NULL, writerfunc, (void *) NULL);
pthread_create(&r1, NULL, readerfunc, (void *) NULL);
pthread_create(&r2, NULL, readerfunc, (void *) NULL);
pthread_join(r1, NULL);
pthread_join(r2, NULL);
pthread_join(w, NULL);
sleep(1);
}
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
pthread_exit(NULL);
return 0;
}