我在大学学习实时系统,我一直在使用带有Arduino的RTOS ChibiOS来应用我学过的东西。 示例代码可以在这里找到: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 */}
它使用序列来显示当前在关键部分中的线程,一次应该是两个。 事情是,在执行示例时,我得到以下模式输出: 1 2 3 2 1,2 2 ......
为什么会这样?不应该是1 2,3 1 1,2 3,1 2,...
线程不应该排队吗?
我一直在使用技术维基中的image来了解它的工作原理。