?也算备忘录吧,看了一段时间的状态机,记录一下
?
?
#include <iostream>
#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/simple_state.hpp>
#include <boost/statechart/transition.hpp>
#include <boost/statechart/custom_reaction.hpp>
using namespace std;
namespace sc = boost::statechart;
namespace mpl = boost::mpl;
#define LOG cout<<endl<<__func__<<":"
//事件&状态定义
struct State_Gloabl; //全局的入口
struct State_Begin;
struct Event_GetUrl : sc::event<Event_GetUrl>{};
struct State_Init;
struct Event_StartDeal : sc::event<Event_StartDeal>{};
struct State_Deal;
struct Event_KeepDeal : sc::event<Event_KeepDeal>{};
struct Event_DealDone : sc::event<Event_DealDone>{};
struct State_End;
string url="";
int32_t process = 0;
//事件->状态的具体实现
struct State_Gloabl : sc::state_machine<State_Gloabl, State_Begin>{
State_Gloabl(){}
};
struct State_Begin : sc::simple_state<State_Begin, State_Gloabl>{
typedef sc::transition<Event_GetUrl, State_Init> reactions;
State_Begin(){
LOG<<"开始处理";
}
};
struct State_Init : sc::simple_state<State_Init, State_Gloabl>{
typedef sc::transition<Event_StartDeal, State_Deal> reactions;
State_Init(){
LOG<<"请输入url:";
cin >> url;
}
};
struct State_Deal : sc::simple_state<State_Deal, State_Gloabl>{
typedef mpl::list<
sc::transition<Event_KeepDeal, State_Deal>,
sc::transition<Event_DealDone, State_End>
> reactions;
State_Deal(){
LOG<<"开始处理,当前进度:"<<process;
}
};
struct State_End : sc::simple_state<State_End, State_Gloabl>{
State_End(){
LOG<<"处理结束";
}
};
/**/
int main()
{
State_Gloabl myMachine;
// 构造完状态机后,它并未开始运行。我们要通过调用它的initiate()来启动它。
// 同时,它也将触发它的初始状态的构造。
myMachine.initiate();
myMachine.process_event(Event_GetUrl());
myMachine.process_event(Event_StartDeal());
for(auto i = 0;i<100; i++){
usleep(500);
process++;
if(i == 99){
myMachine.process_event(Event_DealDone());
}
myMachine.process_event(Event_KeepDeal());
}
return 0;
}
|