Knowledge Base

MultiTrack (Advanced): Transient tasks

It is not necessary for a task to live forever. There can only be a finite number of tasks in the queue at any point time (how many depends on the model of SPLat board), so it may sometimes pay to make a task that is launched when required and terminates itself when it has done its job. That way you not only save on the finite capacity of the queue, but you also make your program run faster because no processor time is wasted processing idle tasks.

The instruction KillTask causes a task to yield without being placed back into the task queue, effectively killing itself. It is not possible for one task to kill another task. However, tasks may LaunchTask each other.

You must take care not to launch multiple copies (called instances) of a task unless that is your exact intention.

Let’s make a push on/push off light switch that flashes a pilot light on output 1 three times each time the button is pressed.

Here’s the main toggle function:

Toggle:         WaitOnK         0
                On              0
                LaunchTask      Blink3
                WaitOnK         0
                Off             0
                LaunchTask      Blink3
                GoTo            Toggle

;Toggle assumes the existence of another task called Blink3.

BlinkCount      defBYTE
Blink3:         SetMem          BlinkCount,3
Blink3Loop:     On              1
                Pause           1
                Off             1
                Pause           1
                YieldTask
                DecMGoIfNZ      BlinkCount,Blink3Loop
                KillTask
Exercise:

Build a program around the two tasks listed, with the necessary LaunchTask and RunTasksForever instructions.

Hint: Blink3 is launched from inside Toggle, so you don’t need to launch it again.

Hint: In simulation you can speed up execution a lot by minimizing the editor window.

Watchit: When you test your program, be careful not to activate the “button” (input 0) while Blink3 is active. This would cause multiple instances (copies) of Blink3 to be launched concurrently. This will produce unexpected results.

Exercise:

Watch the BlinkCount counter in the Data Memory window. It will normally be allocated to location 19. You will see it go to 3 and then count down to 0 each time Blink3 is launched.

Now try clicking the “button” many times, and watch Blink3 playing up. Observe what happens to BlinkCount. Try and explain what you see (but don’t stress if you can’t!)

Exercise:

Use a semaphore in Blink3 to protect against multiple instances being launched and attempting to co-exist.