Skip to content

Event Priority

Sergei Fedorov edited this page Nov 29, 2016 · 1 revision

afsm provides an option to prioritize and change the order enqueued or deferred events are handled. It comes with minor performance penalty - more data must be stored and priority_queue is slower that deque is.

The definition of the state machine doesn't differ from ordinary state machine. It is instantiation that differs. Given that your state machine definition is called my_fsm_def instead of

using my_sm = ::afsm::state_machine<my_fsm_def>;

you should use

using my_priority_sm = ::afsm::priority_state_machine<my_fsm_def>;

If you don't use explicit rebinding to the state machine type inside your state machine definition code, you can freely use both.

The priority_state_machine main and only difference in interface is that the process_event member function template accepts one more optional parameter, ::std::int32_t priority. You can specify the value for each event, or alternatively provide a template ::afsm::event_priority_traits<> specialization for event types to prioritize events by types. The value of the traits template will be used as a default and you can still assign the events individual priorities.

namespace afsm {

template <>
struct event_priority_traits<::my_ns::urgent_event>
        : ::std::integral_constant<event_priority_type, 100500> {};
template <>
struct event_priority_traits<::my_ns::low_priority_event>
        : ::std::integral_constant<event_priority_type, -42> {};

} /* namespace afsm */

void use()
{
    my_priority_sm fsm;
    // Use priority value specified in traits specialization
    fsm.process_event(low_priority_event{});
    // Use priority value specified in traits specialization
    fsm.process_event(urgent_event{});
    // Post event with non-default priority
    fsm.process_event(urgent_event{}, -10);
    // Post event with non-default priority
    fsm.process_event(low_priority_event{}, 10000);
}

Please note that the priority will only affect the order enqueued or deferred events. The events that can be handled immediately will be handled immediately.

Clone this wiki locally