-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate_abort_example.cpp
61 lines (51 loc) · 1.86 KB
/
state_abort_example.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
#include <chrono>
#include <thread>
#include <iostream>
#include <state/State.h>
#include <state/StateManager.h>
struct EndState : public State {
EndState() : State("EndState") {}
NextState run(void) override { return nullptr; }
};
struct BarState : public State {
BarState() : State("BarState") {}
NextState run() override {
std::cout << "Now in " << getName() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
throw std::runtime_error("oopsie!");
return NextState(new EndState());
}
};
struct FooState : public State {
FooState() : State("FooState") {}
NextState run() override {
std::cout << "Now in " << getName() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Going to BarState" << std::endl;
return NextState(new BarState());
}
};
struct StartState : public State {
StartState() : State("StartState") {}
NextState run() override {
std::cout << "Now in " << getName() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Going to FooState" << std::endl;
return NextState(new FooState());
}
};
int main() {
StateManager state_manager(std::unique_ptr<State>(new StartState));
std::thread thread(&StateManager::run, &state_manager);
while(state_manager.isRunning()) {
std::cout << state_manager.getStateName() << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
std::cout << "Last state was " << state_manager.getLastState()->getName() << std::endl;
try {
std::rethrow_exception(std::dynamic_pointer_cast<AbortState>(state_manager.getLastState())->exception);
} catch (const std::exception & e) {
std::cout << "Exception was " << e.what() << std::endl;
}
thread.join();
}