KMotion/KFlop Preemptive Multitasking
KMotion/KFlop uses a simple method of preemptive multitasking (multiple programs or "Threads" running at the same time). Each Thread consists of an area of memory where a program can be loaded, A CPU Stack for that program, and a potential time slice of the CPU. User Programs (Threads) and the System Thread context switch every Servo Interrupt and sequence in a round robin order.
The main thing to understand is that two programs that ever
need to be running at the same time need to be assigned to different threads.
The KFLOP system Thread runs all the time in Thread #0. So Thread #0 may never
be used. In a typical KMotionCNC system the Init.c program is usually assigned
to thread #1 and runs forever. If other UserButtons (or MCodes) run C Programs
that do something and terminate (Exec/Wait option) then these might all be
assigned to use Thread#2. If your programs run for a longer time where a 3rd or
4th program might be Launched so they all overlap in time, then they must all be
assigned to different Threads.
Most Applications have a Red Stop Button that stops all or most Threads from executing. For example KMotion.exe stops all User Threads. KMotionCNC stops all User Threads except Thread #1 so any critical monitoring program might be placed in Thread #1 in order to continue execution after an Emergency Stop.
The above example shows a case where two User Threads are currently active.
The C function WaitNextTimeSlice() can be used to wait until the next context switch occurs and return immediately at the beginning of the next time slice. This can assure that the User Program can execute for a few microseconds without being interrupted and at a very stable rate (with a few microseconds of jitter).
The time period between executions of each user thread is a function of the number of active User Threads:
Period = (# User Threads + 1) * TIMEBASE