有没有办法确保 C 中操作的原子性?

发布于 2024-10-07 05:51:05 字数 485 浏览 0 评论 0原文

我希望这个语句(在 if 语句体内)是原子的:

if(I2C1STATbits.P || cmd_buffer_ptr >= CMD_BUFFER_SIZE - 1)
    cmd_buff_full = 1; // should be atomic

我的处理器 (dsPIC33F) 支持原子位设置和清除。它还支持 16 位寄存器和内存位置的原子写入;这些是单周期的。我如何确定该操作将以原子方式实现 - 有没有办法强制编译器执行此操作?就我而言,我相当确定它会编译为原子性的,但我不希望它在将来发生变化,例如,如果我更改了其他一些代码并重新组织了内容,或者更新了编译器。例如,是否有 atomic 关键字?

我正在使用 GCC v3.23 - 更具体地说,MPLAB C30,一个修改后的 GCC 闭源版本。我正在开发一个微控制器,它只有中断;没有线程的概念。原子性唯一可能的问题是,如果可能的话,可能会在两个周期的写入中间触发中断。

I want this statement (within the body of the if statement) to be atomic:

if(I2C1STATbits.P || cmd_buffer_ptr >= CMD_BUFFER_SIZE - 1)
    cmd_buff_full = 1; // should be atomic

My processor (dsPIC33F) supports atomic bit set and clear. It also supports atomic writes for 16-bit registers and memory locations; these are single cycle. How can I be sure the operation will be implemented in an atomic fashion - is there a way to force the compiler to do this? In my case I'm fairly sure it will compile to be atomic, but I don't want it to change in future if I, for example, change some other code and it reorganises things, or if I update the compiler. For example, is there an atomic keyword?

I'm working with GCC v3.23 - more specifically, MPLAB C30, a modified closed source version of GCC. I am working on a microcontroller, which has only interrupts; there is no concept of threads. The only possible problem with atomicity is that an interrupt may be triggered in the middle of a write over two cycles, if that is even possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

对风讲故事 2024-10-14 05:51:05

根据您希望分配是原子的其他竞争操作,您可以使用 sig_atomic_t。严格来说,这只能保护它免受信号的影响。在实践中,它还提供了原子性。多重三维。

编辑:如果目标是保证存储操作不被编码成两个汇编指令,则有必要使用内联汇编 - C 在这方面不做任何保证。如果目标是防止中断干扰存储操作,则另一种方法是在存储之前禁用中断,然后再启用它们。

Depending on what other competing operations you want the assignment to be atomic, you could use sig_atomic_t. Strictly speaking, this protects it only from the presence of signals. In practice, it also provides atomicity wrt. multi-threeading.

Edit: if the object is to guarantee that the store operation is not coded into two assembler instructions, it will be necessary to use inline assembly - C will make no guarantees in that respect. If the objective is to prevent an interrupt from interfering with the store operation, an alternative is to disable interrupts before the store, and enable them afterwards.

余生一个溪 2024-10-14 05:51:05

不是用 C 语言,但也许您的处理器附带的库中有一个专有的库调用。例如,在 Windows 上,有一个 InterlockedIncrement() 和 InterlockedDecrement() (用于 inc/dec long),保证在没有锁的情况下是原子的。

Not in C, but perhaps there's a proprietary library call in libraries that come with your processor. For example, on Windows, there's an InterlockedIncrement() and InterlockedDecrement() (to inc/dec longs) that's guaranteed to be atomic without a lock.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文