forked from Lowkee1g/DockerContainerForC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.c
More file actions
75 lines (54 loc) · 1.67 KB
/
test.c
File metadata and controls
75 lines (54 loc) · 1.67 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
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t readers_cond;
int counter = 0;
int active_readers = 0;
void* writer(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
// Wait until there are no active readers
while (active_readers > 0) {
pthread_cond_wait(&readers_cond, &mutex);
}
// Increment the counter
counter++;
printf("Writer: Counter incremented to %d\n", counter);
pthread_mutex_unlock(&mutex);
// Break the loop after incrementing the counter
}
pthread_exit(NULL);
}
void* reader(void* arg) {
while (1)
{pthread_mutex_lock(&mutex);
active_readers++;
pthread_mutex_unlock(&mutex);
// Read the counter
printf("Reader: Counter value is %d\n", counter);
pthread_mutex_lock(&mutex);
active_readers--;
// Signal the writer if no more active readers
if (active_readers == 0) {
pthread_cond_signal(&readers_cond);
}
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);}
}
int main() {
pthread_t writer_thread, reader_thread1, reader_thread2;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&readers_cond, NULL);
// Create writer thread
pthread_create(&writer_thread, NULL, writer, NULL);
// Create reader threads
pthread_create(&reader_thread1, NULL, reader, NULL);
pthread_create(&reader_thread2, NULL, reader, NULL);
// Wait for threads to finish
pthread_join(writer_thread, NULL);
pthread_join(reader_thread1, NULL);
pthread_join(reader_thread2, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&readers_cond);
return 0;
}