Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

1 #include <pthread.

h> Max Hailperin wrote this


2 #include <stdbool.h>
3 problem for his textbook
4 pthread_mutex_t m;
5 pthread_cond_t c_child;
Operating Systems and
6 pthread_cond_t c_adult; Middleware. At a child care
center, state regulations
7 int num_children = 0;
8 int num_adults = 0;
9 require that there is always
10 pthread_mutex_lock(&m);
11 while (true) { one adult present for every
12 // If there are 3 or more children and no adults, wait for an adult three children. Puzzle:
13 if (num_children >= 3 && num_adults == 0) {
14 pthread_cond_wait(&c_child, &m); Write code for child
15 } threads and adult threads
16 // If there are no children, wait for a child
17 if (num_children == 0) { 18 pthread_cond_wait(&c_adult, &m); that enforces this
19 } constraint in a critical
20 // If we reach here, there is at least one adult and one child, so we can enter
the critical section section.
21 // TODO: Enter critical section
22 // TODO: Exit critical section
23 }
24 pthread_mutex_unlock(&m);
25 // Child thread
26 void* child_thread(void* arg) {
27 pthread_mutex_lock(&m);
28 num_children++;
29 pthread_cond_signal(&c_adult); // Wake up adults if necessary
30 pthread_mutex_unlock(&m);
31 }
32
33 // Adult thread
34 void* adult_thread(void* arg) {
35 pthread_mutex_lock(&m);
36 num_adults++;
37 pthread_cond_signal(&c_child); // Wake up children if necessary
38 pthread_mutex_unlock(&m);
39 }
40 int main() {
41 // Initialize mutex and condition variables
42 pthread_mutex_init(&m, NULL);
43 pthread_cond_init(&c_child, NULL);
44 pthread_cond_init(&c_adult, NULL);
45
46 // Create child and adult threads
47 pthread_t child1, child2, child3, adult1;
48 pthread_create(&child1, NULL, child_thread, NULL);
49 pthread_create(&child2, NULL, child_thread, NULL);
50 pthread_create(&child3, NULL, child_thread, NULL);
51 pthread_create(&adult1, NULL, adult_thread, NULL);
52
53 // Wait for child and adult threads to finish
54 pthread_join(child1, NULL);
55 pthread_join(child2, NULL);
56 pthread_join(child3, NULL);
57 pthread_join(adult1, NULL);
58
59 // Clean up mutex and condition variables
60 pthread_mutex_destroy(&m);
61 pthread_cond_destroy(&c_child);
62 pthread_cond_destroy(&c_adult);
63
64 return 0;
65 }

You might also like