User`s manual

56 digi.com Multitasking with Dynamic C
5.3 Costatements
Costatements are Dynamic C extensions to the C language which simplify implementation of state
machines. Costatements are cooperative because their execution can be voluntarily suspended and later
resumed. The body of a costatement is an ordered list of operations to perform -- a task. Each costatement
has its own statement pointer to keep track of which item on the list will be performed when the costate-
ment is given a chance to run. As part of the startup initialization, the pointer is set to point to the first
statement of the costatement.
The statement pointer is effectively a state variable for the costatement or cofunction. It specifies the state-
ment where execution is to begin when the program execution thread hits the start of the costatement.
All costatements in the program, except those that use pointers as their names, are initialized when the
function chain _GLOBAL_INIT is called. _GLOBAL_INIT is called automatically by premain before
main is called. Calling _GLOBAL_INIT from an application program will cause reinitialization of any-
thing that was initialized in the call made by premain.
5.3.1 Solving the Real-Time Problem with Costatements
The Dynamic C costatement provides an easier way to control the tasks. It is relatively easy to add a task
that checks for the use of an emergency stop button and then behaves accordingly.
The solution is elegant and simple. Note that the second costatement looks much like the original descrip-
tion of the problem. All the branching, nesting and variables within the task are hidden in the implementa-
tion of the costatement and its waitfor statements.
while(1){
costate{ ... } // task 1
costate{ // task 2
waitfor( buttonpushed() );
turnondevice1();
waitfor( DelaySec(60L) );
turnondevice2();
waitfor( DelaySec(60L) );
turnoffdevice1();
turnoffdevice2();
}
costate{ ... } // task n
}