我在我的嵌入式设备(STM32、GCC)上使用了 protothreads,因为它很轻量级,并且可以让我自己处理复杂的状态机。
随着我的主程序的增长,在大于 256 的行号上调用 PT_* 函数
struct pt main_pt;
int main(void)
{
PT_BEGIN(pt);
while(true)
{
/*... 256 lines further*/
PT_WAIT_UNTIL(pt, flag);
PT_YIELD(pt);
}
PT_END(pt);
}
在编译时,它会抛出这个错误:
main.c: In function 'main':
main.c:256:4: error: case label value exceeds maximum value for type [-Werror]
PT_WAIT_UNTIL(pt, flag);
main.c:257:4: error: case label value exceeds maximum value for type [-Werror]
PT_YIELD(pt);
如果 PT_YIELD 或 PT_WAIT_UNTIL 放置在低于 256 的行号上,它会编译。
这是 PT_YIELD、PT_WAIT_UNTIL、LC_SET 和 struct pt 的片段:
typedef uint32_t lc_t;
struct pt {
lc_t lc;
};
#define LC_RESUME(s) switch(s) { case 0:
#define LC_SET(s) s = __LINE__; case __LINE__:
#define PT_BEGIN(pt) { unsigned int PT_YIELD_FLAG = 1; LC_RESUME((pt)->lc)
#define PT_WAIT_UNTIL(pt, condition) \
do { \
LC_SET((pt)->lc); \
if(!(condition)) { \
return PT_WAITING; \
} \
} while(0)
#define PT_YIELD(pt) \
do { \
PT_YIELD_FLAG = 0; \
LC_SET((pt)->lc); \
if(PT_YIELD_FLAG == 0) { \
return PT_YIELDED; \
} \
} while(0)
为什么“case __LINE__:”不能超过 256,因为它存储在 uint32_t 上?