Parallel modification of double [] [] elements without blocking

I have a gear array double[][]that can be modified simultaneously by multiple threads. I would like to make it thread safe, but if possible without locks. Streams can be well oriented on the same element in the array, so the whole problem arises. I found code to increase double-digit values ​​using the method Interlocked.CompareExchange: Why is there no overload of Interlocked.Add that takes paired numbers as parameters?

My question is: will it remain atomic if Interlocked.CompareExchangethere is a reference to an uneven array? Your understanding is greatly appreciated.

Example:

    public class Example
    {
        double[][] items;

        public void AddToItem(int i, int j, double addendum)
        {
            double newCurrentValue = items[i][j];
            double currentValue;
            double newValue;
            SpinWait spin = new SpinWait();

            while (true) {
               currentValue = newCurrentValue;
               newValue = currentValue + addendum;
               // This is the step of which I am uncertain:
               newCurrentValue = Interlocked.CompareExchange(ref items[i][j], newValue, currentValue);
               if (newCurrentValue == currentValue) break;
               spin.SpinOnce();
            }
        }
    }
+4
2

, - . . , , .

:

double newCurrentValue = items[i][j];

, ( x86). , , - CompareExchange.

+4

, .

, ( ), AddToItem.
, ( , , ).

public class Example
{
    double[][] items;

    public void AddToItem(int i, int j, double addendum)
    {
        var spin = new SpinWait();

        while (true)
        {
            var valueAtStart = Volatile.Read(ref items[i][j]);
            var newValue = valueAtStart + addendum;

            var oldValue = Interlocked.CompareExchange(ref items[i][j], newValue, valueAtStart);

            if (oldValue.Equals(valueAtStart))
                break;
            spin.SpinOnce();
        }
    }
}


, volatile items[i][j]. Volatile.Read , .NET(. ECMA-334 ECMA-335).
( Interlocked.CompareExchange), items[i][j] Volatile.Read.

, , , ( Volatile.Read Interlocked.CompareExchange)

+3

Source: https://habr.com/ru/post/1668377/


All Articles