Function SharedPtr.compareExchange
Compares the SharedPtr
pointers pointed-to by this
and expected
.
bool compareExchange(MemoryOrder success = MemoryOrder .seq, MemoryOrder failure = success, E, D, This)
(
scope ref E expected,
scope D desired
) scope
if (isSharedPtr!E && !is(E == shared) && isSharedPtr!D && !is(D == shared) && isMoveAssignable!(D, This) && isCopyAssignable!(This, E));
If they are equivalent (store the same pointer value, and either share ownership of the same object or are both empty), assigns desired
into this
using the memory ordering constraints specified by success
and returns true
.
If they are not equivalent, assigns this
into expected
using the memory ordering constraints specified by failure
and returns false
.
More info in c++ std::atomic
Examples
//fail
{
SharedPtr!long a = SharedPtr!long .make(123);
SharedPtr!long b = SharedPtr!long .make(42);
SharedPtr!long c = SharedPtr!long .make(666);
a .compareExchange(b, c);
assert(*a == 123);
assert(*b == 123);
assert(*c == 666);
}
//success
{
SharedPtr!long a = SharedPtr!long .make(123);
SharedPtr!long b = a;
SharedPtr!long c = SharedPtr!long .make(666);
a .compareExchange(b, c);
assert(*a == 666);
assert(*b == 123);
assert(*c == 666);
}
//shared fail
{
shared SharedPtr!(shared long) a = SharedPtr!(shared long) .make(123);
SharedPtr!(shared long) b = SharedPtr!(shared long) .make(42);
SharedPtr!(shared long) c = SharedPtr!(shared long) .make(666);
a .compareExchange(b, c);
auto tmp = a .exchange(null);
assert(*tmp == 123);
assert(*b == 123);
assert(*c == 666);
}
//shared success
{
SharedPtr!(shared long) b = SharedPtr!(shared long) .make(123);
shared SharedPtr!(shared long) a = b;
SharedPtr!(shared long) c = SharedPtr!(shared long) .make(666);
a .compareExchange(b, c);
auto tmp = a .exchange(null);
assert(*tmp == 666);
assert(*b == 123);
assert(*c == 666);
}