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.

Pablo Honey
  • 1,074
  • 1
  • 10
  • 23
  • 1
    Why not test it out yourself? – Yuval Itzchakov Mar 09 '16 at 13:15
  • @Alex : it's "my" way to keep 2 decimals precision when casting double to long. – Pablo Honey Mar 09 '16 at 13:18
  • A full `lock` is quite slow. Probably better to use the `SpinLock`... Still the cast would be much faster. – xanatos Mar 09 '16 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*. – Hans Passant Mar 09 '16 at 13:30
  • I'm taking account everything you said so I'm gonna make a SpinLock with double only. Thanks all. – Pablo Honey Mar 09 '16 at 13:35

0 Answers0