atomic_inc

本文介绍ARM架构下如何使用LDREX和STREX指令实现原子加法操作,通过监测地址访问来确保操作的原子性,避免了并发访问时的数据不一致问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

atomic_inc(&v)对变量v用锁定总线的单指令进行不可分解的"原子"级增量操作,避免v的值由于中断或多处理器同时操作造成不确定状态。

X86 用LOCK 指令实现,  不懂

ARM代码如下,  ldrex :

 ARMv6_Architecture.pdf    解释如下   还是不大明白

• LDREX{<cond>} <Rd>, [<Rn>]
This performs a load, then sets a monitor to “watch” the address
• STREX {<cond>} <Rd>, <Rm>, [<Rn>]
This performs a store and returns “success” in Rd if no intervening access
detected by the monitor.

• LDREX{<cond>} <Rd>, [<Rn>]
This performs a load, then sets a monitor to “watch” the address
• STREX {<cond>} <Rd>, <Rm>, [<Rn>]
This performs a store and returns “success” in Rd if no intervening access
detected by the monitor.

• LDREX{<cond>} <Rd>, [<Rn>]
This performs a load, then sets a monitor to “watch” the address
• STREX {<cond>} <Rd>, <Rm>, [<Rn>]
This performs a store and returns “success” in Rd if no intervening access
detected by the monitor.

static inline int atomic_add_return(int i, atomic_t *v)
{
        unsigned long tmp;
        int result;

        __asm__ __volatile__("@ atomic_add_return/n"
"1:     ldrex   %0, [%2]/n"
"       add     %0, %0, %3/n"
"       strex   %1, %0, [%2]/n"
"       teq     %1, #0/n"
"       bne     1b"
        : "=&r" (result), "=&r" (tmp)
        : "r" (&v->counter), "Ir" (i)
        : "cc");

        return result;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值