Paul Koning wrote:
Come to think of it, cooperative multitasking is
trivial, you can code
your own. It looks like this:
for {;;} { task1(); task2(); task3; /* etc */ }
That's only a very restricted case of cooperative multitasking, though
it can nevertheless be useful and effective for many problems. In fact,
this is the model used in the system I'm working on for my employer.
In a normal cooperative multitasking case, you can write tasks that
yield the CPU partway through their execution, and will resume where
they left off, rather than always resuming at the beginning. (For the
case of exactly two such tasks, this is known as "coroutines".)
This means that each task has to have it's own stack, and any additional
state that the compiler uses (e.g. local variables) must be saved and
restored on a task switch. There is no way to portably implement that
in standard C, although in practice it can be done with setjmp() and
longjmp() on most platforms. (Technically that depends on behavior of
setjmp() and longjmp() beyond what is guaranteed by the C standard.)
Many people have gotten the idea that cooperative multitasking is "bad",
or that it isn't "real" multitasking. In reality, there are many
scenarios in which cooperative multitasking is a better solution than
preemptive multitasking. Either type can get you into trouble if you're
not careful.
Eric