开发者

Is there a way to ensure atomicity with an operation in C?

开发者 https://www.devze.com 2023-01-30 04:49 出处:网络
I want this statement (within the body of the if statement) to be atomic: if(I2C1STATbits.P || cmd_buffer_ptr >= CMD_BUFFER_SIZE - 1)

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 impl开发者_如何学编程emented 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消