Oberon RTK

SemaphoreSync

Synchronised access to shared resource using semaphores

Description

This program demonstrates the synchronisation between several kernel threads with semaphores. The program builds upon BlinkPlus. A semaphore is used to gate the access to the serial terminal between to threads.

With cooperative scheduling, protecting shared resources is often not required, since one thread holds control of the processor until is explicitly returns control to the scheduler. However, as demonstrated in this example, if a thread needs to have exclusive accesss to a resource across re-scheduling events, which would allow other threads to interfere, a semaphore can prevent this, and protect the resource. A shared resource can be data, a hardware device, or a virtual device.

Semaphores are implemented using signals.

Kernel Threads

The program uses three kernel threads:

  • one heartbeat thread that blinks an LED on the board (heartbeat);

  • two periodically timed threads writing to the serial terminal, which stands for any resource that must be held reserved and in control of one thread across a kernel rescheduling run (writer).

Both writer threads run at the same period. The first thread claims the semaphore protecting the terminal to write to, and writes part of its message, then returns control back to the scheduler. At this point, without the semaphore, the second thread would be scheduled to run, also writing to the terminal, and thus interfering with the first.

But since the second thread also needs to claim the semaphore before writing, it will be queued and suspended until the first thread has released the semaphore, at which point it will be put on the run-queue by the scheduler. This allows the first thread to write the second part of the message.

As with BlinkPlus, the two writer threads execute the same code.

Since semaphores are based on signals, the cooperative scheduling nature of kernel-v1 is preserved.

Start-up and Run-time

Please refer to BlinkPlus.

Further Reading

Repository

  • <repo>/examples/v3.1/rpi/pico/SemaphoreSync
  • <repo>/examples/v3.1/rpi/pico2/SemaphoreSync
  • <repo>/examples/v3.1/stm/h573i-dk/SemaphoreSync
  • <repo>/examples/v3.1/stm/u585i-iot/SemaphoreSync

Last updated: 17 May 2026