On Friday 25 October 2013 15:07:36 Oliver Kowalke wrote:
2013/10/25 Andrey Semashev
T * expected1 = 0;
T * expected2 = 0; if ( ! a[index].compare_exchange_strong( expected1, expected2) ) {
// expected1 is not NULL, expected1 removed == a[index] contains NULL
}
No, that's not right. If compare_exchange_strong returns false, the operation have failed and a[index] != NULL (at least, that's how compare_exchange_strong have left it). It should be:
T* expected = a[index].load(memory_order_acquire); while (!a[index].compare_exchange_weak(expected, NULL, memory_order_release, memory_order_acquire)) { }
if (expected)
// The expected value was removed from the array
else
// The array element was removed by some other thread
agreed - but shouldn't we use strong memory-order (I remember that Herb S. recommended to use memory_order_strong in one of its sessions)
Weak CAS can spuriously fail but also can be cheaper on some platforms. Spurious failures don't cause any problems in the code above, so weak CAS is preferred.