Is this atomic code correct?

Sean Kelly sean at
Wed Mar 18 19:59:43 PDT 2009

BCS wrote:
> I find my self in need of some thread safe, lock free code to update a 
> value by way of a self referential expression
> x = min(x,y);
> Being the abstraction addict I am, I went for the general solution and 
> came up with this:
> void AtomicEvalAssign(T)(ref T to, lazy T from)
> {
>     T  old;
>     do
>     {
>         old = atomicLoad(to);
>     } while(!atomicStoreIf(to, from(), old));
> }
> AtomicEvalAssign(x, min(x,y));
> My question is; will that work or might the lazy arg not refetch the value?

min() doesn't perform atomic operations (in fact, it probably just takes 
the parameters by value) so it isn't guaranteed to refetch the values.

More information about the Digitalmars-d-learn mailing list