[concurrency-interest] Semantics of compareAndSwapX

David Holmes davidcholmes at aapt.net.au
Fri Feb 14 06:52:16 EST 2014


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.

David
-----

> I ask because Aarch64 allows a lot of variation.  If you use the
> obvious sequence
>
> 1:	ldaxr	x0, [B]		// Exclusive load with acquire
> 	<op(B)>
> 	stlxr	w1, x0, [B]	// Exclusive store with release
> 	cbnz	w1, 1b
>
> which has two half barriers, you don't prevent some reorderings
> because memory accesses can move past their half barriers.  For
> example,
>
> 	// A, B, C are independent memory locations
>
> 	<Access [A]>
>
> 	// atomic_op (B)
> 1:	ldaxr	x0, [B]		// Exclusive load with acquire
> 	<op(B)>
> 	stlxr	w1, x0, [B]	// Exclusive store with release
> 	cbnz	w1, 1b
>
> 	<Access [C]>
>
> could result in
>
>       load[B] -> A -> C -> store[B]
>
> Of course I can use a belt and braces approach such as
>
> 	dmb	ish		// Full barrier
> 1:	ldxr	x0, [B]		// Exclusive load
> 	<op(B)>
> 	stxr	w1, x0, [B]	// Exclusive store
> 	cbnz	w1, 1b
> 	dmb	ish		// Full barrier
>
> but this is rather heavyweight.  Maybe I could get away with
>
> 1:	ldxr	x0, [B]		// Exclusive load
> 	<op(B)>
> 	stlxr	w1, x0, [B]	// Exclusive store with release
> 	cbnz	w1, 1b
> 	dmb	ish		// Full barrier
>
> but I can't tell because I don't know what Unsafe.compareAndSwap() is
> supposed to guarantee.
>
> For what it's worth, GCC 4.8.1's __sync_bool_compare_and_swap() generates
> the first sequence:
>
> 	ldaxr	x3, [x0]
> 	cmp	x3, x1
> 	bne	.L4
> 	stlxr	w4, x2, [x0]
> 	cbnz	w4, .L3
> .L4:
>
> More discussion at
>
> http://lists.infradead.org/pipermail/linux-arm-kernel/2014-Februar
y/229588.html

Andrew.
_______________________________________________
Concurrency-interest mailing list
Concurrency-interest at cs.oswego.edu
http://cs.oswego.edu/mailman/listinfo/concurrency-interest



More information about the Concurrency-interest mailing list