Tales and thoughts from the founder of NormSoft (maker of Pocket Tunes), working and living in St. Croix, USVI

Thursday, February 24, 2005

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.

@ wait

@ r4 should contain an address that points to the semaphore.
.Lacquiresemaphore:
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
b .Lacquiresemaphore

.Lgotsemaphore:
@ do stuff

@ signal

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.

Enjoy!

No comments: