This is slightly off-topic, as it involves implementation rather than the C language.
It frequently comes up in embedded systems that one wishes to ensure that a C-language statement is atomic. One might have available functions or macros to disable or enable interrupts, so one might write:
volatile int sempahore;
DI(); sempahore++; EI();
Whether an increment can be handled atomically depends on the processor, where in memory the variable is located, its size, and on specific decisions the compiler makes.
Other operations that one might wish to ensure atomicity with include assignments, bitfield assignments, tests, etc.
For example, in the code:
volatile unsigned long x;
if (x > 29204) ...
there might be a problem because an asynchronous process may update the variable and cause the test to get inconsistent bytes as it performs the test.
In most cases, one can protect the statements of concern with DI()/EI() or find a way to guarantee atomicity. The issue is that this method of protection can be inefficient. It consumes memory, consumes CPU cycles, and affects the timing of interrupts.
Here is my question:
Has anyone seen any compilers that support guaranteeing that a certain statement or test is atomic?
What I'd be looking for is something like:
#pragma ASSERT_ATOMIC_STATEMENT_START semaphore++; #pragma ASSERT_ATOMIC_STATEMENT_END
The pragmas would advise the compiler to:
a)Try to compile the statement atomically (using a single instruction), and
b)Create an error if it can't be compiled atomically.
This would save the expense of DI()/EI(), or generate an error if the statement can't be compiled atomically.
Is there anything like this in the world?
Thanks, Datesfat