forked from jakaspeh/concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeadlock.cpp
More file actions
85 lines (66 loc) · 1.88 KB
/
deadlock.cpp
File metadata and controls
85 lines (66 loc) · 1.88 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
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <thread>
#include <mutex>
std::mutex m_print;
std::mutex m_bag;
void makeAppleJuice(std::vector<std::string>& bag)
{
std::lock(m_print, m_bag);
std::lock_guard<std::mutex> printGuard(m_print, std::adopt_lock);
std::lock_guard<std::mutex> bagGuard(m_bag, std::adopt_lock);
// std::lock_guard<std::mutex> printGuard(m_print);
std::cout << "Making an apple juice..." << std::endl;
// std::lock_guard<std::mutex> bagGuard(m_bag);
int numApples = 0;
for (std::size_t i = 0; i != bag.size(); i++)
{
if (bag[i] == "a")
{
numApples++;
bag[i] = "x";
}
}
if (numApples < 5)
{
std::cout << "I can not make an apple juice." << std::endl;
}
else
{
std::cout << "I made an excelent apple juice for you." << std::endl;
}
}
void throwOutPear(std::vector<std::string>& bag)
{
std::lock(m_print, m_bag);
std::lock_guard<std::mutex> printGuard(m_print, std::adopt_lock);
std::lock_guard<std::mutex> bagGuard(m_bag, std::adopt_lock);
// std::lock_guard<std::mutex> bagGuard(m_bag);
for (std::size_t i = 0; i != bag.size(); i++)
{
if (bag[i] == "p")
{
bag[i] = "x";
}
}
// std::lock_guard<std::mutex> printGuard(m_print);
std::cout << "I threw out all pears from you bag!" << std::endl;
}
void printItem(const std::string& fruit)
{
std::cout << fruit << " ";
}
int main()
{
std::vector<std::string> bag = {"a", "a", "a", "p", "p", "a", "p", "a"};
std::thread t1(makeAppleJuice, std::ref(bag));
std::thread t2(throwOutPear, std::ref(bag));
t1.join();
t2.join();
std::cout << "Bag: ";
std::for_each(bag.begin(), bag.end(), printItem);
std::cout << std::endl;
return 0;
}