0

I'm studying Real Time Systems at college, and I've been using the RTOS ChibiOS with an Arduino to apply what I've been learning. The example code can be found here: source code.

// Example of counting semaphore
#include <ChibiOS_AVR.h>

// declare and initialize a semaphore for limiting access
SEMAPHORE_DECL(twoSlots, 2);

// data structures and stack for thread 2
static THD_WORKING_AREA(waTh2, 100);

// data structures and stack for thread 3
static THD_WORKING_AREA(waTh3, 100);
//------------------------------------------------------------------------------
static THD_FUNCTION(thdFcn, name) {
 while (true) {

  // wait for slot
  chSemWait(&twoSlots);

    // only two threads can be in this region at a time
    Serial.println((char*)name);

    chThdSleep(1000);

    // exit region
    chSemSignal(&twoSlots);
  }
}
//------------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);
  // wait for USB Serial
  while (!Serial) {}

  // initialize and start ChibiOS
  chBegin(chSetup);

  // should not return
  while(1);
}
//------------------------------------------------------------------------------
void chSetup() {
  // schedule thread 2
  chThdCreateStatic(waTh2, sizeof(waTh2), NORMALPRIO, thdFcn, (void*)"Th 2");

  // schedule thread 3
  chThdCreateStatic(waTh3, sizeof(waTh3), NORMALPRIO, thdFcn, (void*)"Th 3");

  // main thread is thread 1 at NORMALPRIO
  thdFcn((void*)"Th 1");
}
//------------------------------------------------------------------------------
void loop() {/* not used */}

It uses the serial to display what threads are currently in the critical section, which should be two at a time. Thing is, when executing the example, I'm getting the following pattern output: 1 2, 3 2, 1 2, ...

Why is this happening? Shouldn't it be 1 2, 3 1, 2 3, 1 2, ...
Shouldn't the threads be queuing up?

I've been using this image from the technical wiki to understand how it works. enter image description here

Max G
  • 125
  • 1
  • 6
  • Might be worth to also include the code in the question instead of only as a link (maybe a few years from now the GitHub link structure will change, but this question may still be relevant). – apokryfos Jun 20 '16 at 13:39
  • Add some more print statements into `THD_FUNCTION()` to figure out which thread runs first after sleeping. If the sleep timer is course enough then the two sleeping threads may wake and be ready to run on the same tick. In that case, how does the scheduler choose which thread to run first? If the scheduler runs the second sleeper first then I think it would produce the pattern that you're observing. – kkrambo Jun 20 '16 at 20:08

0 Answers0