C atomic read modify write

Viewed 2503

Are there any functions in C to do atomic read-modify-write? I'm looking to read a value, then set to 0, in a single atomic block.

For C++ there is std::atomic::exchange() which is exactly what I'm looking for. Is there something equivalent in C?

Here's the code:

void interruptHandler(void) {
    /* Callback attached to 3rd party device driver, indicating hardware fault */
    /* Set global variable bit masked flag to indicate interrupt */
    faultsBitMask |= 0x1;
}

void auditPoll(*faults) {
    *faults = faultsBitMask;
    /* !!! Need to prevent interrupt pre-empt here !!! */
    /* Combine these two lines to a single read-modify-write? */
    faultsBitMask = 0;
}

The target architecture is PowerPC.

Thanks for the help!

3 Answers

Yes, the <stdatomic.h> header contains a type-generic function atomic_exchange that's very similar to the C++ version:

_Atomic int n = 10;

#include <stdatomic.h>

int main(void) { return atomic_exchange(&n, 0); }

It seems that you want to use atomics with a signal handler. C11 atomic types can do that if they are "lock-free", but usually they are. You can test this property for int with ATOMIC_INT_LOCK_FREE.

For your case you don't even need an atomic exchange function. On an atomic variable

faultsBitMask |= 0x1;

will always be an atomic read-modify-write operation.

If you are using GCC, give the GCC builtin __atomic_exchange or __atomic_compare_exchange_n a try.

Related