https://github.com/mattlack15/pico-threads
Purpose
This is a tiny preemptive threading library for the Raspberry Pi Pico 2W (RP2350). It multiplexes one core of the processor across up to 32 threads, so independent tasks can be written as normal blocking loops instead of one giant loop that has to keep track of where every task is up to.
Features
- Preemptive round-robin scheduling with 200µs time slices
- Context switches take about 2µs (measured on a Pico 2W)
thread_sleep(us)for sleeping in microsecondsthread_park()andthread_unpark()with a built-in permit, sothread_park()returns immediately if the permit is available (if you've used Java'sLockSupport.park(), it works the same way)thread_yield()for giving the processor to another threadthread_spin_lock, a simple spin lock that yields while it waitsthread_exit(), and threads clean themselves up when their entry function returns
Usage
void entry_point() {
while (1) {}
}
int main() {
thread_init(); // Marks the calling thread as the main thread
thread_create(entry_point); // Create a new thread starting at entry_point()
while (1) {}
}
The first thing I tested it with was a little program with three threads: the main thread draws a bar on a small SPI display, one thread reads a potentiometer through the ADC, and one thread drives a stepper motor towards whatever position the potentiometer is set to. Each of them is just a plain loop. Here is the stepper motor thread:
static void step_motor_entry() {
while (true) {
if (target < current) {
for (int i = 3; i >= 0; i--) {
set_state(i);
thread_sleep(2000);
}
current--;
} else if (target > current) {
for (int i = 0; i < 4; i++) {
set_state((i + 1) % 4);
thread_sleep(2000);
}
current++;
}
}
}
Without threads, this would need to be a state machine that remembers which coil it's on and when it last stepped, interleaved with the display code and the ADC code.
How it works
Preemption
thread_init() claims one of the RP2350's hardware timer alarms and sets its callback to the scheduler. Every 200µs the alarm fires an interrupt, the interrupt handler picks the next thread from the ready queue and switches to it, and then it sets the alarm again for the next time slice.
thread_yield() doesn't do anything special, it just forces that same alarm interrupt to fire immediately with hardware_alarm_force_irq(). This means yielding, sleeping, parking and preemption all go through exactly the same code path, which keeps the scheduler very small.
The context switch
When the processor takes an interrupt, the hardware automatically pushes the caller-saved registers (R0-R3, R12, LR, PC and xPSR) onto the current thread's stack. That only leaves the callee-saved registers, which switch_stack pushes itself before swapping the stack pointer to the new thread's stack:
__attribute__((naked)) void switch_stack(thread_t* from, thread_t* to) {
__asm__ volatile (
"vstmdb sp!, {S16-S31} \n" // push vfp registers (wasn't doing this at first, very hard to find bug)
"push {r4-r11, lr} \n" // push callee-saved registers (caller-saved pushed by hardware)
"mov r2, %[sp_offset] \n" // offset to stack pointer in thread struct
"str sp, [r0, r2] \n" // store current stack pointer in 'from' thread
"ldr sp, [r1, r2] \n" // load new stack pointer from 'to' thread
"pop {r4-r11, lr} \n" // pop callee-saved registers
"vldmia sp!, {S16-S31} \n" // pop vfp registers
"bx lr \n" // return to the new thread
:
: [sp_offset] "I" (offsetof(thread_t, context) + offsetof(struct thread_context, stack_pointer))
: "r2"
);
}
When bx lr runs, LR holds a special EXC_RETURN value instead of a normal address, so the processor treats it as returning from the interrupt. It pops the rest of the new thread's registers off of the new stack, and the new thread continues exactly where it was interrupted.
Creating a thread
A brand new thread has never been interrupted, so its stack has to be set up to look like it was. thread_create() allocates a 2KB stack and writes a fake exception frame at the top of it, with the PC pointing at thread_stub (which calls the thread's entry function and then thread_exit()), and the Thumb bit set in xPSR:
// Exception frame setup
sp[0] = (uint32_t) new_thread->id; // R0 (first argument to thread_stub)
sp[1] = (uint32_t) 0x00000000; // R1
sp[2] = (uint32_t) 0x00000000; // R2
sp[3] = (uint32_t) 0x00000000; // R3
sp[4] = (uint32_t) 0x00000000; // R12
sp[5] = (uint32_t) 0x00000000; // LR
sp[6] = (uint32_t) thread_stub; // PC
sp[7] = (uint32_t) (1U<<24); // xPSR (Thumb bit set)
Below that is space for everything switch_stack pops (R4-R11, LR and S16-S31). The LR slot is set to 0xFFFFFFF9, the EXC_RETURN value that tells the processor to pop a standard exception frame and return to thread mode. The first time the scheduler switches to the thread, it "returns" straight into thread_stub.
The ready queue
Ready threads are kept in a circular buffer. The buffer is protected with one of the RP2350's hardware spin locks, and spin_lock_blocking() also disables interrupts, so the scheduler can't preempt a thread halfway through adding something to the queue.
Exiting
A thread can't free its own stack, since it's still running on it. Instead, thread_exit() marks the thread as exited, records it as the "zombie" to destroy, and yields. Right after the next context switch, the new thread frees the zombie's stack and struct, because by then nothing is running on that stack anymore.
Fun Fact
When I first wrote switch_stack I wasn't saving the floating-point registers S16-S31. These are callee-saved, so the hardware doesn't push them for you. Any thread doing floating-point math could have its values silently overwritten by a different thread. As the comment in the code says, this was a very hard bug to find.
Limitations
- It only uses one of the two cores.
- Scheduling is strictly round robin, there are no priorities.
- Sleeping threads aren't kept in a separate timer queue.
thread_sleep()keeps yielding to other threads until enough time has passed, so a sleeping thread still gets scheduled to check the time. - Every thread gets a fixed 2KB stack.