c++ boost 状态机简单case:模拟下载文件

 也算备忘录吧,看了一段时间的状态机,记录一下

 

 

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值