User`s manual

68 digi.com Multitasking with Dynamic C
5.5.8 Solving the Real-Time Problem with Cofunctions
Cofunctions, with their ability to receive arguments and return values, provide more flexibility and speci-
ficity than our previous solutions.
Using cofunctions, new machines can be added with only trivial code changes. Making
buttonpushed() a cofunction allows more specificity because the value returned can indicate a partic-
ular button in an array of buttons. Then that value can be passed as an argument to the cofunctions
turnondevice and turnoffdevice.
5.6 Patterns of Cooperative Multitasking
Sometimes a task may be something that has a beginning and an end. For example, a cofunction to trans-
mit a string of characters via the serial port begins when the cofunction is first called, and continues during
successive calls as control cycles around the big loop. The end occurs after the last character has been sent
and the waitfordone condition is satisified. This type of a call to a cofunction might look like this:
waitfordone{ SendSerial("string of characters"); }
[ next statement ]
The next statement will execute after the last character is sent.
Some tasks may not have an end. They are endless loops. For example, a task to control a servo loop may
run continuously to regulate the temperature in an oven. If there are a a number of tasks that need to run
continuously, then they can be called using a single waitfordone statement as shown below.
costate {
waitfordone { Task1(); Task2(); Task3(); Task4(); }
[ to come here is an error ]
}
Each task will receive some execution time and, assuming none of the tasks is completed, they will con-
tinue to be called. If one of the cofunctions should abort, then the waitfordone statement will abort,
and corrective action can be taken.
for(;;){
costate{ // task 1
wfd emergencystop();
for (i=0; i<MAX_DEVICES; i++)
wfd turnoffdevice(i);
}
costate{ // task 2
wfd x = buttonpushed();
wfd turnondevice(x);
waitfor( DelaySec(60L) );
wfd turnoffdevice(x);
}
...
costate{ ... } // task n
}