I implement a reference counting schema and for this i need interlock facilities but no memory fences (as far as i understand).

Unfortunately only Windows has a InterlockedDecrementNoFence compiler intrinsic. How can i do this with asm inlining? I would need this for gcc/clang too.

有帮助吗?

解决方案

A lack of at least an intrinsic memory fence operation (depending on the platform) is pretty much going to be impossible for the semantics of this operation. For an atomic increment/decrement to work, the other processor have to have some guarantee of seeing the value of the atomic operation before they perform their own operations on the variable, and the visibility of the operations on the variable has to have some guaranteed total order. Memory barriers, even implicit ones such as in strong-memory models like x86 where standard memory operations have acquire/release semantics, are paramount to the correctness of an atomic increment/decrement operation.

Keep in mind that even when the documentation for MSVC/gcc says that there is a memory barrier, on x86 there will not be an actual memory barrier applied (i.e., a MFENCE instruction) due to the strong-memory model of the platform, but rather a lock on the memory bus to ensure the atomicity of the operation. IA64 on the other-hand will require a memory barrier due to the weaker memory model of that platform. The same would also be true for ARM.

其他提示

This isn't a direct answer but an alternative proposal. If you can use C11 (or C++11), how about atomic operations with memory_order_relaxed? Your compiler may generate no memory fence on weak memory model platforms. (It depends compiler vendor/version)

#include <stdatomic.h>

atomic_int var;
int oldval;

oldval = atomic_fetch_sub_explicit(&var, 1, memory_order_relaxed);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top