forked from jakaspeh/concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackagedTaskRestaurant.cpp
More file actions
113 lines (89 loc) · 2.32 KB
/
packagedTaskRestaurant.cpp
File metadata and controls
113 lines (89 loc) · 2.32 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <iostream>
#include <string>
#include <chrono>
#include <queue>
#include <thread>
#include <future>
#include <utility>
std::mutex MUT;
std::queue < std::packaged_task<bool()> > ORDERS;
std::condition_variable CV;
bool CLOSED = false;
void make_break(const int milisec)
{
std::this_thread::sleep_for(std::chrono::milliseconds(milisec));
}
void cooking()
{
while (!CLOSED)
{
std::packaged_task< bool() > cooking_order;
{
std::unique_lock< std::mutex > guard(MUT);
CV.wait(guard, []{return !ORDERS.empty();});
cooking_order = std::move(ORDERS.front());
ORDERS.pop();
}
cooking_order();
}
}
bool cook_the_meal(const std::string meal)
{
if (meal == "hamburger")
{
std::cout << "Cook: I don't make hamburgers!" << std::endl;
return false;
}
else
{
std::cout << "Cook: making the " << meal << std::endl;
make_break(2);
return true;
}
}
std::future<bool> add_order(const std::string meal)
{
std::cout << "Adding order: " << meal << std::endl;
std::packaged_task<bool()> order(std::bind(cook_the_meal, meal));
std::future< bool > result = order.get_future();
std::lock_guard< std::mutex > guard(MUT);
ORDERS.push(std::move(order));
CV.notify_one();
return result;
}
void serve(std::future<bool> meal,
const std::string mealName)
{
if (meal.get())
{
std::cout << "Waiter: serving " << mealName << std::endl;
}
else
{
std::cout << "Waiter: Unfortunately we don't have "
<< mealName << ". Would you mind to order again?"
<< std::endl;
}
}
void serve_orders()
{
std::string mealOrder1 = "steak";
std::string mealOrder2 = "hamburger";
std::string mealOrder3 = "cheesecake";
std::future<bool> meal1 = add_order(mealOrder1);
std::future<bool> meal2 = add_order(mealOrder2);
std::future<bool> meal3 = add_order(mealOrder3);
serve(std::move(meal1), mealOrder1);
serve(std::move(meal2), mealOrder2);
serve(std::move(meal3), mealOrder3);
}
int main()
{
std::thread cook(cooking);
cook.detach();
std::thread waiter(serve_orders);
waiter.detach();
make_break(100);
CLOSED = true;
return 0;
}