User`s manual

Dynamic C Users Manual digi.com 19
3.3 Run DEMO3.C
The example below, sample program DEMO3.C, uses costatements. A costatement is a way to perform a
sequence of operations that involve pauses or waits for some external event to take place.
3.3.1 Cooperative Multitasking
Cooperative multitasking is a way to perform several different tasks at virtually the same time. An exam-
ple would be to step a machine through a sequence of tasks and at the same time carry on a dialog with the
operator via a keyboard interface. Each separate task voluntarily surrenders its compute time when it does
not need to perform any more immediate activity. In preemptive multitasking control is forcibly removed
from the task via an interrupt.
Dynamic C has language extensions to support both types of multitasking. For cooperative multitasking
the language extensions are costatements and cofunctions. Preemptive multitasking is accomplished with
slicing or by using the µC/OS-II real-time kernel.
Advantages of Cooperative Multitasking
Unlike preemptive multitasking, in cooperative multitasking variables can be shared between different
tasks without taking elaborate precautions. Cooperative multitasking also takes advantage of the natural
delays that occur in most tasks to more efficiently use the available processor time.
The DEMO3.C sample program has two independent tasks. The first task prints out a message to Stdio
once per second. The second task watches to see if the keyboard has been pressed and prints the entered
key.
The numbers in the left margin are reference indicators and not part of the code. Load and run the pro-
gram. The elapsed time is printed to the Stdio window once per second. Push several keys and note how
they are reported.
main() {
int secs; // seconds counter
secs = 0; // initialize counter
(1) while (1) { // endless loop
// First task will print the seconds elapsed.
(2) costate {
secs++; // increment counter
(3) waitfor( DelayMs(1000) ); // wait one second
printf("%d seconds\n", secs); // print elapsed seconds
(4) }
// Second task will check if any keys have been pressed.
costate {
(5) if ( !kbhit() ) abort; // key been pressed?
printf(" key pressed = %c\n", getchar() );
}
(6) } // end of while loop
} // end of main