[cpp-threads] Failed compare-and-swap
Howard Hinnant
howard.hinnant at gmail.com
Wed Aug 1 18:54:02 BST 2007
On Aug 1, 2007, at 1:17 PM, Herb Sutter wrote:
> It seems like there are two legitimate choices:
>
> - CAS returns the old value, in which case a failed CAS should at
> least by default have acquire semantics because it's a read.
>
> - CAS returns only a success/fail boolean, in which case a failed
> CAS need not have any ordering semantics.
>
> Does that make sense? It seems we can happily choose either, but the
> choice affects the return type.
Lawrence recently generously sent me the following semantics for the
compare_swap function proposed in N2324:
bool atomic_compare_swap( volatile atomic_integral* a, integral*
old_v, integral new_v)
{
if (a == x)
{
*a = new_v;
return true;
}
*old_v = *a;
return false;
}
I've been using this to good effect in the mutex work I've been doing:
...
do
{
count = old_state & __num_waiting;
--count;
new_state = (old_state & ~__num_waiting) | count;
} while (!compare_swap(&__state_, &old_state, new_state));
old_state = new_state;
...
Having both the "false" and the updated state in "old_state" on a
failed CAS is extremely convenient. I really like the N2324 interface
in this regard. And if I'm understanding correctly, this means a
failed CAS should have read/acquire semantics.
-Howard
More information about the cpp-threads
mailing list