-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingleThreadExecution.cpp
More file actions
65 lines (57 loc) · 1.63 KB
/
SingleThreadExecution.cpp
File metadata and controls
65 lines (57 loc) · 1.63 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
/** 増補改訂版 Java 言語で学ぶデザインパターン入門 【マルチスレッド編】p58 SingleThreadExecution.cpp **/
#include <thread>
#include <mutex>
#include <iostream>
class Gate
{
public:
void pass(std::string name, std::string address)
{
//この排他制御を入れるか入れないかで結果が変わる。
std::lock_guard<std::mutex> lock(m_gate);
m_counter++;
m_name = name;
m_address = address;
check();
}
std::string toString()
{
return "No." + std::to_string(m_counter) + " : " + m_name + ", " + m_address;
}
private:
int m_counter = 0;
std::string m_name = "Nobody";
std::string m_address = "Nowhere";
std::mutex m_gate;
void check()
{
if(m_name.at(0) != m_address.at(0))
{
std::cout << " ******** BROKEN ******** " << toString() <<std::endl;
}
}
};
int main()
{
auto PasstheGate = [](Gate & gate, const std::string& name, const std::string& address)
{
std::cout << name << " BEGIN." << std::endl;
while(true){
gate.pass(name, address);
}
};
Gate gate;
std::string Alice_name = "Alice";
std::string Alice_address = "Alaska";
std::thread AliceThread(PasstheGate, std::ref(gate), std::ref(Alice_name), std::ref(Alice_address));
std::string Bobby_name = "Bobby";
std::string Bobby_address = "Brazil";
std::thread BobbyThread(PasstheGate, std::ref(gate), std::ref(Bobby_name), std::ref(Bobby_address));
std::string Chris_name = "Chris";
std::string Chris_address = "Canada";
std::thread ChrisThread(PasstheGate, std::ref(gate), std::ref(Chris_name), std::ref(Chris_address));
AliceThread.join();
BobbyThread.join();
ChrisThread.join();
return 0;
}