我注意到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_and
,fetch_or
和fetch_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;
}
任何想法为什么会这样?这是因为你不能使用按位操作的锁前缀(据我所知,不是真的吗?)