State machine vs. context switching
I'm currently writing a driver that handles multiple peripheral devices which require a complex initialization procedure. There may be hundreds of them and each one can be different. Doing the procedure one-by-one and step-by-step would take a long time because I have to wait for the network communication after each step. So I have to process the devices concurrently. There is no way to do this with cogs because I would soon run out of them.
The common way to handle this is with state machines. This means that the code has multiple big and nested switch/case statements to decide what has to be done next for each device and for each network packet. This makes the code look ugly.
The alternative method would be to do some sort of "soft" multitasking. The idea is to start a process for each device. This way the initialization procedure can be coded sequentially. Each process simply runs from the beginning to the end. Each time it needs to wait it calls a ContextSwitch() function that transfers control to another process by exchanging the stack pointer so that the return from ContextSwitch() jumps to a different location (the point where the other process called ContextSwitch() last time).
This works similar to the RESIx instructions: The next time the interrupt is invoked it is not executed from the beginning of the ISR but resumes after the last RESIx instruction.
Question @ersmith: Is this possible at all? I mean, when I use FlexProp can I assume that all context information is on the stack or is there some hidden state stored somewhere else (cog registers, LUT etc.)?