gpt4 book ai didi

c++ - 通过 constexpr 的临界区

转载 作者:行者123 更新时间:2023-11-30 00:53:35 25 4
gpt4 key购买 nike

在嵌入式编程中,需要创建代码的原子部分 - 所谓的临界区。它们通常通过宏来实现,例如,像这样:

#define ENTER_CRITICAL() int saved_status_ = CPU_STATUS_REGISTER; __disable_irq();
#define EXIT_CRITICAL() CPU_STATUS_REGISTER = saved_status_

即进入中断状态(启用或禁用)被保存;退出时 - 它已恢复。问题是为此需要额外的变量。

我的问题是:是否可以通过 constexpr 函数创建关键部分(并摆脱宏)?

最佳答案

RAII 解决方案将是传统的:

struct CriticalSection {
int saved_status_;
void Enter() {
saved_status_ = CPU_STATUS_REGISTER;
__disable_irq();
}
CriticalSection() { Enter(); }
void Exit() {
CPU_STATUS_REGISTER = saved_status_;
}
~CriticalSection() {
Exit(); // Can you call this more than once safely? Dunno.
}
};

你会像这样使用它:

void foo() {
// unprotected code goes here
{
CriticalSection _;
// protected code goes here
}
// unprotected code goes here
}

在没有任何状态的情况下执行此操作是不可能的,因为 CPU_STATUS_REGISTER 是一个运行时值。 C/C++ 中的状态主要存储在变量中。

我强烈怀疑,在任何重要的优化级别下,上述 RAII 类将编译为与您的宏编译为完全相同的代码,只是您不再需要记住 EXIT_CRITICAL()。

关于c++ - 通过 constexpr 的临界区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16058901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com