Test the thread switching time by implementing semaphore ping-pong between two threads.
Measure thread switching time by implementing semaphore ping-pong between two threads
This mbed program starts two threads with realtime-priority. Each of them is waiting for the other to give its semaphore and gives the other thread's semaphore as a reaction. Once started, this algorithm results in fast thread switches, enforced by the semaphores.
To allow measurement, one thread sets a GPIO output, while to other one clears it.
Measurements are performed on a NUCLEO-F767ZI board https://os.mbed.com/platforms/ST-Nucleo-F767ZI/.
mbed-os-5.12.3
Measured gpio_out output frequency, whitch contains actually two thread switches:
- 6.5 - 7.0 usec (154 kHz - 143 kHz)
Diff: main.cpp
- Revision:
- 0:ea879e5f3ce5
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Sat May 11 13:58:02 2019 +0000 @@ -0,0 +1,50 @@ +/* + Test thread switching time using semaphore ping-pong + + Hardware: NUCLEO-F767ZI + Libraries: + mbed-os-5.12.3 + Measured gpio_out output frequency, + which contains actually two thread switches: + 6.5 - 7.0 usec (154 kHz - 143 kHz) +*/ + +#include "mbed.h" + +Semaphore semaphore_on(0); +Semaphore semaphore_off(0); + +DigitalOut gpio_out(PC_8); + +void run_on() +{ + while (true) { + semaphore_on.wait(); + gpio_out = 1; + semaphore_off.release(); + } +} + +void run_off() +{ + while (true) { + semaphore_off.wait(); + gpio_out = 0; + semaphore_on.release(); + } +} + +int main() +{ + Thread *thread_on = new Thread(osPriorityRealtime); + Thread *thread_off = new Thread(osPriorityRealtime); + + thread_on->start(run_on); + thread_off->start(run_off); + + semaphore_on.release(); + + while (true) { + wait(0.1); // 100 ns + } +}