|
Forum Index : Microcontroller and PC projects : Coming soon to a CMM2 near you - Basic multi-tasking
| Author | Message | ||||
| matherp Guru Joined: 11/12/2012 Location: United KingdomPosts: 12288 |
25 November 2026. Work in progress: threads are not in any release yet, and the details may still change. Comments and ideas are welcome. MMBasic has long had interrupts: something happens, a short routine runs, and the program carries on. Threads are a different tool. A thread is an ordinary SUB that runs alongside the main program for as long as it likes, with its own loops, its own LOCAL variables and its own PAUSEs. The firmware shares the processor between the threads, a millisecond at a time. Option Explicit Dim Integer beats Sub Heart Do Inc beats Pause 500 ' the rest of the program runs meanwhile Loop End Sub Thread Start 1, Heart Do Text 0, 0, "Beats: " + Str$(beats) + " " Pause 100 Loop Until Inkey$ <> "" End ' the threads stop with the program What works today These run on a test board now: • THREAD START n, sub starts thread n (1 to 16) running a SUB. The main program is thread 0. • THREAD EXIT ends the thread that runs it. A thread also ends when its SUB ends. • THREAD YIELD gives up the rest of the thread's time slice. • THREAD STOP n ends thread n where it stands. Its local variables and memory are freed. • THREAD PAUSE n and THREAD RESUME n hold thread n and let it go on. • THREAD SLICE ms sets the time slice, 1 to 100 ms. It is 1 ms unless you say otherwise. • THREAD SIZE kb [, locals] sets the stack and the number of local variables for threads started after it. • MM.INFO(THREAD) is the number of the thread that runs it. MM.INFO(THREAD n) is 0 if thread n is not running, 1 if it is running, 2 if it is in a PAUSE and 3 if it has been paused. Still to come: locks (THREAD LOCK and UNLOCK), THREAD HOLD and RELEASE for a few statements that must not be split, THREAD WAIT (for a thread to end, or for a flag), arguments for a thread's SUB, and THREAD LIST. How they work • One thread runs at a time, and the switch comes only between statements, never in the middle of one. A statement is always whole: Inc count in two threads never loses a count. • The threads take turns, 1 ms each, in number order. A thread whose PAUSE has just ended goes next, so things that are timed stay on time among busy threads. • Each thread has its own LOCAL variables, FOR and DO loops, SUB and FUNCTION calls, GOSUBs, ON ERROR setting with MM.ERRNO and MM.ERRMSG$, and place in the DATA for READ. Two threads can run the same SUB at the same time, each with its own locals, recursion included. • Everything else is shared: global variables and arrays, STATIC variables, the screen with its current colours, font and print position, open files, sound, the pins and the options. • PAUSE in a thread costs nothing. The other threads run meanwhile, and a program whose threads are all waiting is idle. • Interrupts work as before (SETTICK, SETPIN, ON KEY and the rest). Their routines always run in the main program, whichever thread was running when the interrupt came, and no thread runs until the routine returns. • END in any thread, an error in any thread, or Ctrl-C stops the whole program. An error says where it was: "Error in thread 3, line 5". • OPTION COMPILE ON works with threads. • The cost: a program that starts no thread runs as fast as before. A switch takes about 5 microseconds, so 1 ms slices cost about half a percent. A thread takes about 37 KB of memory while it runs, given back when it ends. What they cannot do • They do not make a program faster. There is one processor: four busy threads get a quarter of it each. Threads are for doing several things at once, not for doing one thing sooner. • They cannot cut into a statement. A statement that takes a long time (a SORT of a large array, a file copy, loading a picture, INPUT waiting for the user) holds every thread until it is done. For now PAUSE is the only wait that lets the others run, so read keys with INKEY$ in a loop, not with INPUT. Later INPUT and the other commands that wait will let the others run too. • No priorities. Every thread that is ready gets its turn. • No arguments for the thread's SUB yet. Until there are, MM.INFO(THREAD) tells a SUB which thread it is, to pick its row of an array (the second example). • Limits: with the usual sizes a thread can go about nine FUNCTIONs deep (SUB calls take nothing) and have 48 local variables, and about ten threads can run at once. THREAD SIZE changes that: more stack for deep recursion, or fewer locals each for all sixteen threads. • Not allowed in a thread: RUN, CHAIN, FLASH RUN, LIBRARY LOAD, MsgBox() and GUI CLICK. Not allowed while any thread is running: ERASE, REDIM, CLEAR, SAVE CONTEXT and LOAD CONTEXT. THREAD START is for programs, not the command prompt, and CONTINUE does not work after Ctrl-C in a program with threads. The one thing to watch: what the threads share A switch can come between any two statements. Suppose two threads do this: ' thread 1 ' thread 2 Colour RGB(red) Colour RGB(green) Print "Alarm!" Print "All well" If the switch comes after thread 1's COLOUR, "Alarm!" is printed in green. Until the locks arrive there are three simple ways round it: • One owner. One thread does all the drawing, or all the writing to a file, and the others only set variables for it. • One statement. Text x, y, "Alarm!", , , , RGB(red) carries its colour with it, and nothing can come between. • One writer. A variable that one thread sets and the others only read is always safe. A test and the action after it are two statements, so If free > 0 Then free = free - 1 can be cut in the middle when two threads run it. Inc, and a single assignment, cannot. Ideas for using them • Something with a rhythm of its own: a clock in the corner, a heartbeat LED, a status line, a tune played note by note with a PAUSE between the notes while the game goes on. • Straight-line code in place of a state machine: traffic lights, a sequence of valves and timers, an alien that moves, waits and fires. Each is written as steps with PAUSEs between them, not as a SETTICK routine and a variable that remembers where it had got to. • Many of the same thing: every ball, alien or robot is the same SUB in a thread of its own, with its own LOCALs (the second example). • A long job with a live screen: a Mandelbrot or a big calculation runs in a thread while the main program shows progress and reads the keys, and can pause it, let it go on or stop it (the third example). • Logging: one thread samples a sensor every 100 ms into an array, another writes the array to the SD card every ten seconds, and the main program draws the graph. • Communications: a thread watches a COM port or the network, puts the lines together and leaves each one in a global for the main program. • A timeout: a thread that waits five seconds and then sets a flag, or stops another thread. Thread or interrupt? An interrupt is for something that happens and wants a quick, short answer. A thread is for something that goes on: it waits, loops and has a flow of its own. They work well together: the interrupt sets a variable and a thread acts on it. Two more examples Four balls, one SUB. Each thread runs Ball with its own x, y, dx and dy. Each CIRCLE carries its own colour, so the threads cannot mix them up. Option Explicit Dim Integer i Dim Integer col(4) = (0, RGB(red), RGB(green), RGB(yellow), RGB(cyan)) Sub Ball Local Integer me = MM.Info(Thread) Local Float x = 100 * me, y = 60 * me, dx = 2 + me, dy = 1 + me Do Circle x, y, 5, 1, 1, 0, 0 ' rub the old one out x = x + dx : y = y + dy If x < 10 Or x > MM.HRes - 10 Then dx = -dx If y < 10 Or y > MM.VRes - 10 Then dy = -dy Circle x, y, 5, 1, 1, col(me), col(me) Pause 20 Loop End Sub CLS For i = 1 To 4 : Thread Start i, Ball : Next Do : Pause 50 : Loop Until Inkey$ <> "" End A long job that listens. The picture is drawn by a thread. The main program reads the keys: P pauses the drawing, R lets it go on, Q stops it. Option Explicit Dim Integer done, row Dim k$ Sub Picture Local Integer x, y For y = 0 To MM.VRes - 1 For x = 0 To MM.HRes - 1 Pixel x, y, RGB(x And 255, y And 255, (x Xor y) And 255) Next row = y Next done = 1 End Sub CLS Thread Start 1, Picture Do While done = 0 k$ = UCase$(Inkey$) If k$ = "P" Then Thread Pause 1 If k$ = "R" Then Thread Resume 1 If k$ = "Q" Then Exit Do Pause 50 Loop Thread Stop 1 ' (does nothing if the thread has ended) Print @(0, 0) "Ended at row"; row |
||||
| PhenixRising Guru Joined: 07/11/2023 Location: United KingdomPosts: 2171 |
Another dream come true I would have been ecstatic with four or eight but sixteen is even better I have always used the state-machine approach which is still a nice solution but PAUSE needs to be a non-blocking timer. Threads are more like true multi-tasking. Fantastic |
||||
| PhenixRising Guru Joined: 07/11/2023 Location: United KingdomPosts: 2171 |
First thought: Can the stepper interrupt still run? |
||||
| matherp Guru Joined: 11/12/2012 Location: United KingdomPosts: 12288 |
If you mean the underlying H/W interrupt, those are completely unaffected Edited 2026-11-26 01:01 by matherp |
||||
| LeoNicolas Guru Joined: 07/10/2020 Location: CanadaPosts: 627 |
I can foresee some race condition bugs that will come to haunt developers Jokes aside, I never thought I would see threads on the BASIC language Amazing jobs Peter |
||||
| Volhout Guru Joined: 05/03/2018 Location: NetherlandsPosts: 6295 |
Hi Peter, Some 5 years ago I asked Geoff for "multi tasking" since PICAXE offers this (max 4 threads) on some devices. (i.e. 20M2). @37k per thread, this is a no-go for the non-PSRAM pico's. Volhout PicomiteVGA PETSCII ROBOTS |
||||
| matherp Guru Joined: 11/12/2012 Location: United KingdomPosts: 12288 |
This one has been on my to-do list forever but whereas the AI can analyse the whole of MMbasic to plan the approach, that is probably beyond me holding it all in my head at once. The beauty of the approach is already yielding real benefits in my dev testing. Start a thread to get user input with the INPUT or LINE INPUT routines which are currently completely blocking and now other processing can carry on. Reading from a ds18b20 is no longer blocking if it is read in a thread etc.... |
||||
| matherp Guru Joined: 11/12/2012 Location: United KingdomPosts: 12288 |
At the moment this is a cmm2 only capability however, if it will translate to the PicoMite at all then the memory usage can be already be tuned using: THREAD SIZE kb [, locals] sets the stack and the number of local variables for threads started after it. The stack can be quite low if the thread isn't itself calling many nested subroutines and if it doesn't use many locals. The final code will also allow setting stack and local parameters on a per thread basis. I see no reason it couldn't be fully usable on an RP2040 let alone an RP2350 |
||||
| PhenixRising Guru Joined: 07/11/2023 Location: United KingdomPosts: 2171 |
Slick Re: RP2350. I am using all eight PIDs and all at the same rate. It just feels a bit clunky, having them in separate ISRs (latency?). If we had this 1ms thread on the PicoMite, would I get the same priority? Thinking about doing all PIDs in one CSUB. |
||||
| bfwolf Senior Member Joined: 03/01/2025 Location: GermanyPosts: 284 |
Do you plan to add methods for inter-thread communication or thread synchronization, such as messages, semaphores, or mutexes? Many of these can be implemented using counting semaphores (with a defined maximum value) — e.g. mutexes can then be created by limiting a counting semaphore to values of 0 and 1. If I recall correctly, most synchronization tools in FreeRTOS are ultimately built using just a few basic primitives. Regards. |
||||
| JohnS Guru Joined: 18/11/2011 Location: United KingdomPosts: 4407 |
As most statements are atomic (actioned completely once started) you already have all that's needed I think. John |
||||
| bfwolf Senior Member Joined: 03/01/2025 Location: GermanyPosts: 284 |
Not when interacting with hardware, e.g. writing to GPIOs.. Or e.g. when accessing the same file and seeking to positions.. => Mutex .. Many jobs need more than 1 BASIC statement. bfwolf |
||||
| matherp Guru Joined: 11/12/2012 Location: United KingdomPosts: 12288 |
some things you have to code yourselves |
||||
| JohnS Guru Joined: 18/11/2011 Location: United KingdomPosts: 4407 |
As most statements are atomic (actioned completely once started) you already have all that's needed I think. John Not when interacting with hardware, e.g. writing to GPIOs.. Or e.g. when accessing the same file and seeking to positions.. => Mutex .. Many jobs need more than 1 BASIC statement. bfwolf At least one kind of non-busy interlock would be wise, for sure. John |
||||
| The Back Shed's forum code is written, and hosted, in Australia. | © JAQ Software 2026 |