Optimal state machine implementation in C
In the fifth lesson in the state machine segment on Embedded.com, I introduce the state machine implementation in C that I consider optimal according to the criteria I explain. The companion video lesson #39 shows how to build a reusable “event processor” to include this optimal state machine implementation strategy directly in the “MicroC/AO” active object framework you started designing in the lesson about event-driven active objects.
Why is it "Optimal"?
To arrive at an optimal solution, it often helps to imagine what that ideal should look like and then work backward to implement it in a programming language like C.
So, let’s imagine that you are inventing a domain-specific language (DSL), not so much to implement state machines but to specify them in the most succinct way you can think of. Such a DSL will then be a textual representation of the state machine diagrams.
The video illustrates this thought process, where you first transcribe the TimeBomb state diagram without thinking of the C syntax. You start with states as the top elements and then fill in their internal structure, capturing entry/exit actions, transitions, and guards.
领英推荐
Comparison with SMC
The State Machine Compiler (SMC) is another popular translation-based state machine implementation technique. This method uses an “easy-to-understand state machine language” (DSL), which the SMC can translate into several programming languages, including C and C++.
The video shows the TimeBomb state machine specified in the SMC language, which is remarkably similar to your state handler functions. In fact, the SMC DSL is not more straightforward or expressive than the direct state-handler-based implementation in C.
The whole indirection layer of the SMC DSL and the translation step only make sense because the final state machine implementation is based on the object-oriented “State” design pattern [3], which is relatively complex and prone to coding errors, especially in a non-OO language like C.
Embedded Software Engineer
1 年I am reading your book, I admire having a visual image of a software system an idea I am fond of, I am learning alot not only then but also I had lot of notes, gonna share it with you once I finalize the chapter I am in :)
Back-end Software Engineer | Java, Kotlin, SQL, MongoDB | Spring Boot, Microservices, REST API, Cloud...
1 年The concept of imagining an ideal DSL for succinctly specifying state machines is a brilliant approach. It's intriguing to see the comparison with SMC, emphasizing the direct state-handler-based implementation's simplicity. Cutting through unnecessary indirection layers can indeed lead to more straightforward, error-resistant code.
Software Engineer at Prosaris
1 年Looking forward to watching this one Miro