|
Forum Index : Microcontroller and PC projects : Coming soon to a CMM2 near you - Basic multi-tasking
| Page 1 of 2 |
|||||
| Author | Message | ||||
| matherp Guru Joined: 11/12/2012 Location: United KingdomPosts: 12301 |
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: 2175 |
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: 2175 |
First thought: Can the stepper interrupt still run? |
||||
| matherp Guru Joined: 11/12/2012 Location: United KingdomPosts: 12301 |
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: 6303 |
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: 12301 |
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: 12301 |
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: 2175 |
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: 286 |
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: 286 |
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: 12301 |
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 |
||||
| Mixtel90 Guru Joined: 05/10/2019 Location: United KingdomPosts: 9402 |
set/reset a system flag? Mick Zilog Inside! nascom.info for Nascom & Gemini |
||||
| matherp Guru Joined: 11/12/2012 Location: United KingdomPosts: 12301 |
Here is the threads manual for review/comment. It should answer many of the questions Colour_Maximite_2_Threads_User_Manual.pdf |
||||
| AlbertR Senior Member Joined: 29/05/2025 Location: GermanyPosts: 115 |
I have to say that the fantastic developments that have been put together here in such a short time are a little intimidating. I can only marvel at it all and express my sincere admiration for everyone driving this forward, especially Peter(When on earth does he find the time to do all that? ), who is doing an incredible job here. I can barely keep up with everything and feel like I can’t contribute anything. Someone here on the forum once said it’s like being in a candy store—you bounce back and forth excitedly, marveling at everything, and I’m already getting a little dizzy from all the sugar.I was just about to post my cooperative scheduler for discussion before yesterday, then I saw this thread . Now I'm just sharing it for informational purposes. It's based on jobs, and the math functions helped speed them up quite a bit.I adapted Peter's examples for this. Option explicit Option default none '- Scheduler-consts -----------------------------------------------------------| Const MaxEntry = 16 ' num of Job-Slots variable Const QueMask = 15 ' num of Queue-slots - 1; have to be 2^n - 1 Const MaxTOut = 15 ' max Soft-Timeouts Const KFree = 1e30 ' Mark Slot free(float) Const KRun = 5e29 ' Mark Slot still in use(float) Const KPAUS = &hfffffffffff0' Mark Slot paused(int) Const E_LISTFULL = 1 ' id MaxEntry reached Const E_QUEFULL = 2 ' id Queue overrun Const E_NOSLOT = 3 ' id JobNext by no Job in List '- Scheduler-Variablen --------------------------------------------------------| Dim float JKey(MaxEntry-1) ' to time / KFree / KRun Dim integer JArg(MaxEntry-1) ' Job-parameter( use not spezific) Dim JFunc(MaxEntry-1) As string length 20 ' Sub-Name (max. 20 char) Dim QFunc(QueMask) As string length 20 ' Queue: Sub-name Dim integer QArg(QueMask) ' Queue: Par Dim float TDue(MaxTOut) ' Soft-Timeouts: expiration time (KFree = inactiv) Dim integer ErrCnt(3) ' error-counter Dim integer SchedRun ' state of sequencer 0=stop Dim integer CurSlot ' Slot of runnung Job (-1: eject Job) '==============================================================================| Dim integer col(4) = (0,RGB(red),RGB(green),RGB(yellow),RGB(cyan)) Type circle_atr x As float y As float dx As float dy As float End Type Dim cir(4) As circle_atr Dim integer res, i, row '- start ---------------------- JobListInit ' allways the first step: init the Joblists JobAdd "KeyCheck", 0, 0 JobAdd "Picture", 1, 0 CLS Sequencer() ' start scheduler res = JobRemove("Picture", -1)' or JobListInit Print @(0, 0) "Ended at row"; row Pause 2000 CLS For i = 1 To 4 cir(i).x = 70*i:cir(i).y = 50*i:cir(i).dx = 2+i: cir(i).dy = 1+i JobAdd "Ball", i, 0 Next Sequencer() ' start Print @(0, 0) "Demo ended" End '- Jobs -----------------------------------------------------------------------| Sub Ball(i As integer) JobNext i, 20 ' plan an other turn; without this the Job ends here Circle cir(i).x, cir(i).y, 5, 1, 1, 0, 0 ' rub the old one out cir(i).x = cir(i).x + cir(i).dx : cir(i).y = cir(i).y + cir(i).dy If cir(i).x < 10 Or cir(i).x > MM.HRES - 10 Then cir(i).dx = -cir(i).dx If cir(i).y < 10 Or cir(i).y > MM.VRES - 10 Then cir(i).dy = -cir(i).dy Circle cir(i).x, cir(i).y, 5, 1, 1, col(i), col(i) End Sub Sub Picture(id%) Static integer y = 0 Local Integer x For x = 0 To MM.HRES - 1 Pixel x, y, RGB(x And 255, y And 255, (x Xor y) And 255) Next Inc y row = y If y < MM.VRES Then JobNext id%, 0' as soon as possible Else SchedStop EndIf End Sub Sub KeyCheck(par%) Local string k$ JobNext 0, 50 k$ = UCASE$(Inkey$) If k$ = "P" Then JobRetrig("Picture", 1, KPAUS ) If k$ = "R" Then JobRetrig("Picture", 1, 0) If k$ = "Q" Then SchedStop 'If Inkey$ <> "" Then SchedStop End Sub '== sequencer ================================================================| Sub JobListInit() Local integer i For i = 0 To MaxEntry-1 JKey(i) = KFree Next For i = 0 To 3 ErrCnt(i) = 0 Next For i = 0 To MaxTOut TDue(i) = KFree Next SchedRun = 1 CurSlot = -1 Timer = 0 End Sub 'insert(start) Job with time-slot (delay in ms, 0 = next turn) Sub JobAdd(func$, par%, delay%) Local integer gFi Local float gFv gFv = Math(Max JKey(), gFi) ' greatest value = Slot free If gFv < KFree Then Inc ErrCnt(E_LISTFULL): Exit Sub ' no Slot free JKey(gFi) = Timer + delay% JFunc(gFi) = func$ JArg(gFi) = par% End Sub ' running Job plans himself ones more (reuse Slot). Sub JobNext(par%, delay%) If CurSlot < 0 Then Inc ErrCnt(E_NOSLOT): Exit Sub JKey(CurSlot) = Timer + delay% JArg(CurSlot) = par% End Sub ' remove all Jobs with name func$ (and Parameter = par%; par% = -1: all) Function JobRemove(func$, par%) As integer Local integer cnt, i cnt = 0 For i = 0 To MaxEntry-1 If JKey(i) < KRun Then If JFunc(i) = func$ And (par% = -1 Or JArg(i) = par%) Then JKey(i) = KFree Inc cnt End If End If Next JobRemove = cnt End Function 'give an exiting Job a new expire-time Sub JobRetrig(func$, par%, delay%) Local integer i For i = 0 To MaxEntry-1 If JKey(i) < KRun Then If JFunc(i) = func$ And JArg(i) = par% Then JKey(i) = Timer + delay% Exit Sub End If End If Next JobAdd func$, par%, delay% End Sub ' Timeout starten bzw. neu starten (Retrigger) Sub SetTimeOut(idx%, delay%) TDue(idx%) = Timer + delay% End Sub Sub CancelTimeOut(idx%) TDue(idx%) = KFree End Sub ' 1 = abgelaufen (in zeitkritischen Tasks direkt: If TDue(idx) <= Timer Then ...) Function TimedOut(idx%) As integer TimedOut = (TDue(idx%) <= Timer) End Function Sub Sequencer Local integer p1, mi Local float fv, t0 Local nm As string length 20 SchedRun = 1 Do fv = Math(Min JKey(), mi) If fv < Timer Then ' because of float equal is unlikely JKey(mi) = KRun ' mark running, decide about FREE later CurSlot = mi Call JFunc(mi), JArg(mi) If JKey(mi) = KRun Then JKey(mi) = KFree ' no JobNext -> make Slot free End If Loop Until SchedRun = 0 End Sub Sub SchedStop SchedRun = 0 End Sub Albert |
||||
| bfwolf Senior Member Joined: 03/01/2025 Location: GermanyPosts: 286 |
Colour_Maximite_2_Threads_User_Manual.pdf I’ve taken a "quick" look through the manual: it seems to contain everything necessary for thread synchronization. With "THREAD HOLD" and "THREAD RELEASE," one can temporarily block thread switching — useful, for instance, when combining flags with other data structures, such as implementing a ring buffer for messages using arrays of strings. It would be helpful if "THREAD WAIT FLAG f [, timeout]" also implicitly performed a "THREAD RELEASE" in cases where the same thread had previously executed "THREAD HOLD". That would make the entire operation "atomic." Perhaps this is already the case, but simply not yet documented? And by the way: Regards, bfwolf. |
||||
| matherp Guru Joined: 11/12/2012 Location: United KingdomPosts: 12301 |
Thanks for reading it so closely. At the moment THREAD WAIT FLAG inside THREAD HOLD is an error ("Cannot wait while the threads are held") unless the flag is already set; the manual says so under THREAD HOLD. You don't need it for a correct ring buffer, though: a flag stays set until a thread clears it, so if the consumer clears the flag inside its hold when it finds the buffer empty, then releases and waits, a message put in between still wakes it. What you describe, releasing the hold for the wait and taking it again on waking, is a condition variable, and it would make that pattern shorter and harder to get wrong. It's on the list for a later beta, and the next manual will have a worked queue example. |
||||
| matherp Guru Joined: 11/12/2012 Location: United KingdomPosts: 12301 |
V8.00.00b5 now posted on the cmm2 beta thread including the full threads implementation |
||||
| Page 1 of 2 |
|||||
| The Back Shed's forum code is written, and hosted, in Australia. | © JAQ Software 2026 |