在开关盒内阻塞

Blocking inside a switch case

在嵌入式系统上,运行 freertos,有没有什么原因可以在 switch 语句的 case 中没有阻塞函数?

例如线程运行通过一个状态机,其中一个状态是等待任务通知。

通常情况下,我使用 if-else 来完成此操作,但将其作为 switch case 有什么优点或缺点吗?

使用 cpp17 并避免使用 STL。

编辑:阻塞函数,即永远等待直到收到通知的函数,例如 xTaskNotifyWait(...)

示例:

switch (state)
{
case state1:
  foo();
  break;
case state2:
  xTaskNotifyWait(...);
};

if (state == state1)
{
  foo();
}
else if (state == state2)
{
  xTaskNotifyWait(...);
}

TIA

您可以使用 switchif 语句。没有太大区别。您可以在其中任何一个中进行阻塞调用。

I've heard that switch cases use hash tables but if-else doesn't. I'm not sure if there are differences in the asm code, and what impact that would have on code size, speed, etc.

请参阅 this 以了解 switch 和 if 语句之间的区别。我引用以下答案之一:

The main difference is that switch despatches immediately to the case concerned, typically via an indexed jump, rather than having to evaluate all the conditions that would be required in an if-else chain, which means that code at the end of the chain is reached more slowly than code at the beginning.

That in turn imposes some restrictions on the switch statement that the if-else chain doesn't have: it can't handle all datatypes, and all the case values have to be constant.

使用 switch 构造,您可以使用描述性 enum 作为您的案例标签,表示此状态应为 blocking。我个人会使用 switch 构造,因为案例标签可以是描述性的。

enum state_e {
    INIT,
    WAITING_FOR_EVENT
};

switch (state) {
case INIT:
{
  foo();
  state = WAITING_FOR_EVENT;
  break;
}
case WAITING_FOR_EVENT:
{
  xTaskNotifyWait(...);
  // Change State
  break;
}
};