-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFsm.cpp
114 lines (77 loc) · 1.54 KB
/
Fsm.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
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
#include "Fsm.h"
#include <mutex>
#include "State.h"
using std::once_flag;
using std::call_once;
using std::unique_lock;
namespace
{
once_flag flag;
}
shared_ptr<FSM> FSM::instance = nullptr;
shared_ptr<FSM> FSM::GentInstance()
{
call_once(flag, [] {
instance.reset(new FSM);
});
return instance;
}
void FSM::BuildStateChart()
{
}
shared_ptr<State> FSM::FootPrint()
{
lock_guard<mutex> gu(lock);
return curState;
}
void FSM::UpdateFootPrint(shared_ptr<State> s)
{
lock_guard<mutex> gu(lock);
curState = s;
}
shared_ptr<State> FSM::SearchState(const string name)
{
if (states.find(name) != states.end())
return states[name];
return nullptr;
}
void FSM::Birth()
{
for (auto iter = states.begin(); iter != states.end(); ++iter)
{
if (iter->second->IsInitial())
{
iter->second->OnEnter();
return;
}
}
}
void FSM::Feed(const Event& msg)
{
{
unique_lock<mutex> cvLock(eventLock);
messageQue.push(msg);
}
cv.notify_all();
return;
}
void FSM::Consume(const Event& event)
{
vector<Event> availableMsg;
{
unique_lock<mutex> cvLock(eventLock);
cv.wait(cvLock, [this]{
return !messageQue.empty();
});
while (!messageQue.empty())
{
availableMsg.push_back(messageQue.front());
messageQue.pop();
}
}
for (const auto& iter : availableMsg)
{
if (curState)
curState->Feed(iter);
}
}