为什么fetch_add使用锁定前缀而fetch_and在boost atomics中使用cmpxchg

时间:2015-05-11 12:01:05

标签: c++ assembly boost x86 atomic

我注意到fetch_add的boost :: atomics库x86实现(一个不使用编译器内在函数)使用带有add前缀的lock指令:

static BOOST_FORCEINLINE storage_type fetch_add(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT
{
    __asm__ __volatile__
    (
        "lock; xaddw %0, %1"
        : "+q" (v), "+m" (storage)
        :
        : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA "memory"
    );
    return v;
}

fetch_andfetch_orfetch_xor通过CAS指令实现:

#define BOOST_ATOMIC_DETAIL_CAS_LOOP(op, argument, result)\
    __asm__ __volatile__\
    (\
        "xor %%" BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER ", %%" BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER "\n\t"\
        ".align 16\n\t"\
        "1: movw %[arg], %%dx\n\t"\
        op " %%ax, %%dx\n\t"\
        "lock; cmpxchgw %%dx, %[storage]\n\t"\
        "jne 1b"\
        : [res] "+a" (result), [storage] "+m" (storage)\
        : [arg] "q" (argument)\
        : BOOST_ATOMIC_DETAIL_ASM_CLOBBER_CC_COMMA BOOST_ATOMIC_DETAIL_TEMP_CAS_REGISTER, "memory"\
    )

static BOOST_FORCEINLINE storage_type fetch_and(storage_type volatile& storage, storage_type v, memory_order) BOOST_NOEXCEPT
{
    storage_type res = storage;
    BOOST_ATOMIC_DETAIL_CAS_LOOP("andw", v, res);
    return res;
}

任何想法为什么会这样?这是因为你不能使用按位操作的锁前缀(据我所知,不是真的吗?)

0 个答案:

没有答案