forked from mpavezb/cpp_concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercise_3.cpp
More file actions
68 lines (57 loc) · 1.5 KB
/
exercise_3.cpp
File metadata and controls
68 lines (57 loc) · 1.5 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
#include <chrono>
#include <cstdio>
#include <iostream>
#include <queue>
#include <thread>
void cleaners(std::queue<bool> &queue) {
while (true) {
if (!queue.empty()) {
queue.pop();
printf("Cleaning ...\n");
std::this_thread::sleep_for(std::chrono::seconds(1));
} else {
printf("No cleaning orders ...\n");
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
}
void workers(std::queue<bool> &queue) {
while (true) {
if (!queue.empty()) {
queue.pop();
printf("Working ...\n");
std::this_thread::sleep_for(std::chrono::seconds(1));
} else {
printf("No work orders ...\n");
std::this_thread::sleep_for(std::chrono::seconds(2));
}
}
}
int main() {
std::queue<bool> clean_queue;
std::queue<bool> work_queue;
std::thread cleaners_thread(cleaners, std::ref(clean_queue));
std::thread workers_thread(workers, std::ref(work_queue));
cleaners_thread.detach();
workers_thread.detach();
printf("Starting ... \n");
std::this_thread::sleep_for(std::chrono::seconds(1));
int command_no;
while (true) {
std::cout << "\nEnter a command {1=clean,2=work,100=exit} : ";
std::cin >> command_no;
if (command_no == 1) {
printf("<clean>\n");
clean_queue.push(true);
} else if (command_no == 2) {
printf("<work>\n");
work_queue.push(true);
} else if (command_no == 100) {
printf("<exit>.\n");
break;
} else {
printf("<unknown command>\n");
}
}
return 0;
}