|
Boost : |
Subject: [boost] [MSM] Comparison with ad-hoc FSM implementation
From: Phil Endecott (spam_from_boost_dev_at_[hidden])
Date: 2009-12-08 05:07:09
Dear All,
When we reviewed Andrey Semashev's proposed FSM library last year
I presented a couple of examples of simple state machines encoded
"ad hoc", i.e. primarily as switch statements that set the next
state based on the current state and inputs, and asked "why is
this library better?". I'm going to ask the same question of MSM.
Consider the example presented in the documentation:
struct cd_player_fsm {
enum state_t { Stopped, Open, Empty, Playing, Paused };
enum event_t { play, open_close, stop cd_detected, pause, end_pause };
state_t state;
void process_event(event_t event) {
if (state==Stopped && event==play) { start_playback(); state=Playing; }
else if (state==Stopped && event==open_close) { open_drawer(); state=Open; }
else if (state==Stopped && event==stop) { state=Stopped; }
else if (state==Open && event==open_close) { close_drawer(); state=Empty; }
else if (state==Empty && event==open_close) { open_drawer(); state=Open; }
else if (state==Empty && event==cd_detected
&& good_disk_format()) { store_cd_info(); state=Stopped; }
etc. etc.
}
};
Of course one difference is that MSM has O(1) dispatch. We can
get that too if we use a switch statement, maybe something like:
switch ((state<<8) | event) {
case (Stopped<<8)|play: start_playback(); state=Playing; break;
case (Stopped<<8)|open_close: open_drawer(); state=Open; break;
etc. etc.
The greatest advantage of this ad-hoc style is that it is readable
by anyone who has even the most basic understanding of C++ without
the need to learn a new library, and its exact behaviour is immediately
evident. It is also likely to compile and run quickly.
I have no doubt that MSM has many benefits compared to this. Perhaps
it would be useful to spell them out?
Regards, Phil.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk