我在大学学习实时系统,我一直在使用带有 Arduino 的 RTOS ChibiOS 来应用我一直在学习的东西。示例代码可以在这里找到:源代码。
// 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 */}
它使用序列号来显示当前在临界区中有哪些线程,一次应该是两个。问题是,在执行示例时,我得到以下模式输出:1 2, 3 2, 1 2, ...
为什么会这样?不应该是 1 2, 3 1, 2 3, 1 2, ...
线程不应该排队吗?
我一直在使用技术 wiki 中的这张图片来了解它是如何工作的。