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!
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.
如果您正在使用GCC,请尝试GCC内置 __atomic_exchange
或__atomic_compare_exchange_n
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.