[concurrency-interest] Semantics of compareAndSwapX

Andrew Haley aph at redhat.com
Fri Feb 14 05:41:35 EST 2014


What are the semantics of Unsafe.compareAndSwapX?  The javadoc is
rather thin.

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-February/229588.html

Andrew.


More information about the Concurrency-interest mailing list