简体   繁体   中英

How to implement the __sync_fetch_and_sub atomic operation in assembly language based on Linux GCC

I need to write the implementation of __sync_fetch_and_sub atomic operation myself in assembly language based on GCC 3.4 which doesn't have __sync_fetch_and_sub builtins. But I know little about assembly.

Can anyone help me? Any help would be greatly appreciated!!

here is the implementation of __sync_fetch_and_add

inline unsigned int __sync_fetch_and_add(volatile unsigned int* p, unsigned int incr)
{

    unsigned int result;
    __asm__ _volatile_ ("lock; xadd %0, %1" :
            "=r"(result), "=m"(*p):
            "0"(incr), "m"(*p) :
            "memory");
    return result;
}

__sync_fetch_and_add(int *ptr, int a_count) is to atomically add a_count to the variable pointed by ptr. return the value that had previously in memory.

__sync_fetch_and_sub(int *ptr, int a_count) is to atomically subtract a_count from the variable pointed by ptr. return the value that had previously in memory.

This snippet uses the atomic version of xadd : exchange and add: it atomically add the right operand to the left (here to memory) and returns the initial value in memory in the right operand. The lock statement before ensure the atomicity of the operation.

However, gcc uses the AT&T notation, so the left and right arguments in this explanation (taken from the intel manual) are reversed.

As there is no xsub instruction on intel architecture, the easiest way to emulate this is first to take the opposite of the number you want to substract and then add/exchange it atomically:

inline unsigned int __sync_fetch_and_sub(volatile unsigned int* p,
    unsigned int decr)
{
    unsigned int result;

    __asm__ __volatile__ ("lock; xadd %0, %1"
            :"=r"(result), "=m"(*p)
            :"0"(-decr), "m"(*p)
            :"memory");
    return result;
}

I also remove the unsigned properties, I don't find they are relevant in this case.

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.

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