I assume this is thoroughly discussed but I don’t have the vocabulary to find it.
I am trying to effectively write a simulation of a device that runs code.
I am interested in writing the simulation using Python or MATLAB, preferably in a single thread.
For concreteness imagine a motorized cart with an obstacle sensor on it.
The cart is meant to drive forward until an obstacle is present.
There are two pieces of logic to this simulation, and both demand control flow:
- Cart logic
Collect sensor data. If no obstacle is present, drive forward. Otherwise, stop the cart. Repeat.
- Simulation logic
If the cart is moving forward, increment its position. Pass simulated obstacle data to the carts sensor, based on the cart’s position. Increment a time counter. Repeat.
A bad way of writing this code is to break each loop into a state machine.
Each state would be written as a function that reads and updates some global state structure.
The simulation program loops indefinitely, updating the state over and over again until some stopping condition is met.
This is a bad approach because it is unnatural and hard to debug.
If one built the cart physically, the natural expression of the cart’s control logic is the loop, not the state machine.
I can think of another way of doing this using multiple threads or inter-process communication, but this seems odd and unusual to me.
I have several directly-related questions:
- What is the correct terminology for talking about this situation?
- Are there ways other than multi-threading, without enormous dependencies, that avoid writing the “state-machine-like” version of the code?
Christian Chapman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.