Monday 29 September 2008

Semaphores in Redcode

I'm looking for suggestions on how to code busy-waiting semaphores in Redcode.  The lack of an atomic test-and-set operation complicates matters.
The code below works for up to three processes, but under certain circumstances can fail with four processes.  The entry points are wait and signal.

semaphore: dat 1
....
fail: add #1, semaphore
wait: djn fail, semaphore
.....
signal: add #1, semaphore

If you have any suggestions, please let me know in the comments below.

3 comments:

Unknown said...

Here it is a solution

sem: dat 0,1 ;semaphore
ref: dat 0,-1 ;pointer
wait: djn 0,>-1
task: ...
...
set: mov #1,<ref ;sets semaphore to on

Should work with any number of processes.

Anonymous said...

Not sure if I got it correctly (never worked with semaphores) but might this be correct too?

sem nop 0,0
wait djn.a #0,}0

task
set mov.a #1,{signal

Anonymous said...

Small correction, label wasn't defined, it should be:

sem: nop 0,0
wait: djn.a #0,}0

task:

set: mov.a #1,{wait