-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsleep_barber_problem.cpp
70 lines (61 loc) · 2.11 KB
/
sleep_barber_problem.cpp
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
const int n = 100;
class sleep_barber_problem {
private:
enum barber_status { asleep, conscious };
enum barber_chair_status { idle, busy };
const int number_of_chairs = n;
int customers_waiting[n];
int number_of_customers = 0;
barber_status barber = asleep;
barber_chair_status barber_chair = idle;
int current_customer_on_barber_chair = 0;
public:
void in_customer(int customer_id);
};
void sleep_barber_problem::in_customer(int customer_id) {
int my_index;
do {
if (number_of_customers >= n) {
// Customer leaves if all chairs are occupied.
return;
} else if (number_of_customers == 0) {
// Store my index in queue
my_index = number_of_customers - 1;
customers_waiting[number_of_customers++] = customer_id;
// Wake up the barber
barber = conscious;
} else if (number_of_customers < number_of_chairs) {
// Store my index in queue
my_index = number_of_customers - 1;
customers_waiting[number_of_customers++] = customer_id;
}
while (barber_chair == busy)
; // Wait until the chair is idle.
int j = current_customer_on_barber_chair;
while (j !=
(current_customer_on_barber_chair + number_of_customers - 1) %
n) {
if (j != my_index + (n - 1) % n) {
// Wait until previous customer in the queue before me is
// served.
j = current_customer_on_barber_chair;
} else if (barber_chair == idle) {
// Go to barber room when chair is idle.
j = (j + 1) % n;
break;
}
}
// Action on barber chair
barber_chair = busy;
current_customer_on_barber_chair = customer_id;
// Actions on barber chair
// Exit barber room
barber_chair = idle;
if (--number_of_customers == 0)
barber = asleep;
} while (true);
}
void sleep_barber_problem() {
class sleep_barber_problem sbp;
return;
}