简体   繁体   English

C原子读取修改写入

[英]C atomic read modify write

Are there any functions in C to do atomic read-modify-write? C中是否有任何函数可以进行原子读 - 修改 - 写? I'm looking to read a value, then set to 0, in a single atomic block. 我想在一个原子块中读取一个值,然后设置为0。

For C++ there is std::atomic::exchange() which is exactly what I'm looking for. 对于C ++,有std :: atomic :: exchange(),这正是我正在寻找的。 Is there something equivalent in C? 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. 目标架构是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: 是的, <stdatomic.h>头包含一个类型泛型函数atomic_exchange ,它与C ++版本非常相似:

_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. 看来你想要将atomics与信号处理程序一起使用。 C11 atomic types can do that if they are "lock-free", but usually they are. 如果它们是“无锁”的话,C11原子类型可以做到这一点,但通常它们是。 You can test this property for int with ATOMIC_INT_LOCK_FREE . 您可以使用ATOMIC_INT_LOCK_FREEint测试此属性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM