[concurrency-interest] Semantics of compareAndSwapX
Andrew Haley
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.
> (http://lists.infradead.org/pipermail/linux-arm-kernel/2014-February/229588.html)
>
> <Access [A]>
>
> // atomic_op (B)
> 1: ldxr x0, [B] // Exclusive load
> <op(B)>
> 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)
long oldval;
unsigned long res;
+ smp_mb();
+
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"
"2:"
: "=&r" (res), "=&r" (oldval), "+Q" (ptr->counter)
: "Ir" (old), "r" (new)
: "cc", "memory");
+ smp_mb();
return oldval;
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.
Ah, good.
Andrew.
More information about the Concurrency-interest
mailing list