0

I'm looking for the better way to do Interlocked.Add(ref double, double).

First Way, with Interlocked.Add(ref long, long) and some casting

On a parallel loop:

Interlocked.Add(ref ltotalUpSeconds,  (long) (av.totalUpSeconds * 1000));

Then outside the loop

totalUpSeconds =  ltotalUpSeconds/1000D;

Second way, with a lock :

lock (parallelocker)
{
    totalUpSeconds += av.TotaUpSeconds;
}

I use to hear that lock is slower than Interlocked. But is the loose of performance worths the readability of the lock ?

NB : I don't mind about loosing precision.

5
  • 1
    Why not test it out yourself? Mar 9, 2016 at 13:15
  • @Alex : it's "my" way to keep 2 decimals precision when casting double to long. Mar 9, 2016 at 13:18
  • A full lock is quite slow. Probably better to use the SpinLock... Still the cast would be much faster.
    – xanatos
    Mar 9, 2016 at 13:23
  • "Faster" is of no concern, this is just plain wrong. You now have two variables, one of which you do not update atomically. So non-zero odds that the ltotalUpSeconds you use in the division is stale, the same effect as not using Interlocked. Just much harder to debug since it happens less frequently. If it has to be double then you'll have to take the lock. If it has to be micro-optimized then just call it totalUpMilliseconds. Mar 9, 2016 at 13:30
  • I'm taking account everything you said so I'm gonna make a SpinLock with double only. Thanks all. Mar 9, 2016 at 13:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.