Skip to content

Instantly share code, notes, and snippets.

@PetarKirov
Created January 25, 2021 10:50
Show Gist options
  • Save PetarKirov/8590707f5a21347dc4684b77d092cf60 to your computer and use it in GitHub Desktop.
Save PetarKirov/8590707f5a21347dc4684b77d092cf60 to your computer and use it in GitHub Desktop.
Atomic(T) type in D
unittest
{
shared Atomic!int ai;
assert(ai.get == 0); // atomicLoad / std::atomic<T>::load
ai = 5; // atomicStore via opAssign / std::atomic<T>::operator=
assert(ai.get == 5); // atomicLoad
assert(ai.exchange(3) == 5); // atomicExchange / std::atomic<T>::exchange
assert(ai.get == 3); // atomicLoad
assert(ai.cas(3, 42)); // cas / std::atomic<T>::compare_exchange_strong
assert(ai.get == 42); // atomicLoad
assert(++ai == 43); // atomicFetchAdd / std::atomic<T>::operator++
assert((ai += 10) == 53); // atomicFetchAdd / std::atomic<T>::operator+=
assert((ai -= 3) == 50); // atomicFetchSub / std::atomic<T>::operator-=
assert(--ai == 49); // atomicFetchSub / std::atomic<T>::operator--
// assert(ai++ == 49); // atomic post-increment is not supported.
// assert(ai == 49); // implicit cast is not supported
assert(cast(int)ai == 49); // explicit cast via opCast / atomicLoad / std::atomic<T>::operator T
}
struct Atomic(T)
{
import core.atomic : atomicLoad, atomicStore, atomicCas = cas, atomicOp, atomicExchange;
private shared T _value;
shared(T)* ptr() shared { return &_value; }
bool cas(T oldVal, T newVal) shared
{
return atomicCas(ptr, oldVal, newVal);
}
@property T get() shared
{
return _value.atomicLoad;
}
T opCast(U : T)() shared
{
return get;
}
void opAssign(T newVal) shared
{
_value.atomicStore(newVal);
}
T exchange(T desired) shared
{
return atomicExchange(&_value, desired);
}
T opOpAssign(string op)(T rhs) shared
{
return _value.atomicOp!(op ~ `=`)(rhs);
}
T opUnary(string op)() shared
{
static if (op == `++`)
return _value.atomicOp!`+=`(1);
static if (op == `--`)
return _value.atomicOp!`-=`(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment