2

    public static class InterlockedEx
{
    // AddToTotal safely adds a value to the running total.
    public static float Add(ref float totalValue,float addend)
    {
        float initialValue, computedValue;
        do
        {
            // Save the current running total in a local variable.
            initialValue = totalValue;

            // Add the new value to the running total.
            computedValue = initialValue + addend;

            // CompareExchange compares totalValue to initialValue. If
            // they are not equal, then another thread has updated the
            // running total since this loop started. CompareExchange
            // does not update totalValue. CompareExchange returns the
            // contents of totalValue, which do not equal initialValue,
            // so the loop executes again.
        } while (initialValue != Interlocked.CompareExchange(
            ref totalValue, computedValue, initialValue));
        // If no other thread updated the running total, then 
        // totalValue and initialValue are equal when CompareExchange
        // compares them, and computedValue is stored in totalValue.
        // CompareExchange returns the value that was in totalValue
        // before the update, which is equal to initialValue, so the 
        // loop ends.

        // The function returns computedValue, not totalValue, because
        // totalValue could be changed by another thread between
        // the time the loop ends and the function returns.
        return computedValue;
    }
}

you can call the add like 'Interlocked.Add(ref int32,int32) or Interlocked.Add(ref int64,int64)'

i called it like this: InterlockedEx.Add(ref subtotalVolume[i], v.Volume);

who can give a advice ,make it run right anyway.

the function's result is not equal the normal function(not use TPL).

huoxudong125
  • 1,966
  • 2
  • 26
  • 42
  • 1
    Are you using the return value for addition? If so, you shouldn't. BTW: This is virtually an exact copy of the example provided in the Interlocked.CompareExchange msdn entry (the double overload). – Willem van Rumpt Jan 23 '13 at 09:16
  • thanks for your reply,first. I didn't using the return value for addition. and i copyed and modified the msdn example,but the result had a little offset then i compute without multithreads(No parallel).I am so confused! I referenced example of the book 'CLR Via c#' – huoxudong125 Jan 24 '13 at 01:39
  • i find there is a same question [link](http://stackoverflow.com/questions/1400465/why-is-there-no-overload-of-interlocked-add-that-accepts-doubles-as-parameters) – huoxudong125 Jan 25 '13 at 01:50

0 Answers0