digitalmars.D.learn - Is this atomic code correct?
- BCS (15/15) Mar 17 2009 I find my self in need of some thread safe, lock free code to update a v...
- Sean Kelly (3/22) Mar 18 2009 min() doesn't perform atomic operations (in fact, it probably just takes...
- BCS (3/7) Mar 18 2009 Hmmm. I wonder how that mixes with it being a delegate. I guess inlining...
- Sean Kelly (4/13) Mar 19 2009 Yeah. It would probably actually work with the current DMD, but if a
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?
Mar 17 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.
Mar 18 2009
Hello Sean,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.Hmmm. I wonder how that mixes with it being a delegate. I guess inlining and whatnot would make a difference. Ug.
Mar 18 2009
BCS wrote:Hello Sean,Yeah. It would probably actually work with the current DMD, but if a compiler inlined the call to min it could cache the result in a register and reuse it.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.Hmmm. I wonder how that mixes with it being a delegate. I guess inlining and whatnot would make a difference. Ug.
Mar 19 2009