Real Semaphores on PalmOS 5
It turns out it's fairly easy to implement real binary semaphores on PalmOS 5. This is really handy for folks that want to perform synchronization between their audio callback thread and their UI thread, for instance. Unfortunately, you have to access the semaphore from ARM-native code.
The trick is the SWP ARM instruction. This instruction swaps the contents of a register and a memory location, and it guarantees that this will be an atomic operation.
Here's some sample code in ARM assembly:
@ initialize a 4-byte word value to 1. That initializes your semaphore.
@ r4 should contain an address that points to the semaphore.
mov r5, #0
swp r5, r5, [r4] @ try to set the semaphore to 0
cmp r5, #1 @ if the previous value was 1, then we got it
beq .Lgotsemaphore @ this is a busy wait, but you could insert
@ an OS call - perhaps SysTaskDelay - to make it better
@ do stuff
mov r5, #1
str r5, [r4] @ reset the semaphore
Of course you can extend this example to implement more complicated semaphores as well.
The advantage of this versus a spin lock is that you don't need to know which thread you are executing in. With a 2-slot spin lock, you need to know if you are user #1 or #2.