[concurrency-interest] Semantics of compareAndSwapX
aph at redhat.com
Fri Feb 14 10:31:04 EST 2014
On 02/14/2014 02:46 PM, Doug Lea wrote:
> On 02/14/2014 08:12 AM, Andrew Haley wrote:
>> On 02/14/2014 11:52 AM, David Holmes wrote:
>>> Andrew Haley writes:
>>>> What are the semantics of Unsafe.compareAndSwapX? The javadoc is
>>>> rather thin.
>>> They are the implementation for the associated AtomicX.compareAndSet methods
>>> and so have to adhere to the specification of those methods. But in terms of
>>> memory barriers the key factor is that the variables act as volatiles so the
>>> semantics are of a volatile read combined with a volatile write.
>> Yes, but is that all?
> That's all wrt ordering effects, but CAS must also be atomic.
> For ARMv8/Aarch64 (which I suspect you have in mind), the best mapping
> is likely the one now used in linux.
> <Access [A]>
> // atomic_op (B)
> 1: ldxr x0, [B] // Exclusive load
> stlxr w1, x0, [B] // Exclusive store with release
> cbnz w1, 1b
> dmb ish // Full barrier
> <Access [C]>
Okay, but if you have a look at the patch in that email you will see
that the sequence for CAS is different:
static inline long atomic64_cmpxchg(atomic64_t *ptr, long old, long new)
unsigned long res;
asm volatile("// atomic64_cmpxchg\n"
-"1: ldaxr %1, %2\n"
+"1: ldxr %1, %2\n"
" cmp %1, %3\n"
" b.ne 2f\n"
-" stlxr %w0, %4, %2\n"
+" stxr %w0, %4, %2\n"
" cbnz %w0, 1b\n"
: "=&r" (res), "=&r" (oldval), "+Q" (ptr->counter)
: "Ir" (old), "r" (new)
: "cc", "memory");
Note that this has a full barrier at each end.
> Aside: The JMM update is likely to finally pin down
> multiple modes of CAS/WeakCAS (full, acquire, release),
> which are not all that common, but are specializable into
> more efficient mappings on some processors.
More information about the Concurrency-interest