How to perform multi-threaded operations at random positions in one array?

I have a process that performs many tasks at random positions in Arrayand would like to speed it up with multithreading.

In fact, this is the randomization of a position in the Array, checking its close environment for its values ​​and changing the values ​​of a random position if several specific conditions are met.

Is it possible to run something like

Parallel.For(0, n, s => { });

instead of the code snippet shown below to optimize this function and what will the code block look like for this?

I was thinking about using some “busy” property for the selected elements, but this greatly complicates the task that may be required.

public void doStuffTothisArray(ref int[,,] Array, ref IGenerator randomGenerator, int loops)
{
    int cc = 0;
    int sw = 0;
    do
    {
        if (doStuffOnRandomPositions(ref Array, ref randomGenerator))
            sw++; //if stuff was made counter

        if ((cc % (loops / 10)) == 0)
            Console.Write("{0} % \t", (cc / (loops / 10)) * 10); //some loading info

        cc++; //count iterations
    } while (cc < loops);
    Console.WriteLine("Stuff altered in {0} iterations: {1}", loops, sw);
}

Edit Post:

, .

dostuff..()

public static bool doStuffOnRandomPositions(ref lattice A, ref IGenerator rr)
{
    position firstPos = new position(rr.Next(0, A.n_size),rr.Next(0, A.n_size),rr.Next(0, A.n_size));
    position secondPos = randomNeighbour(ref A, firstPos, ref rr);

    //checks the closest 3d neighbours indexer the lattice
    //Console.WriteLine("first:[{0},{1},{2}]\nsecond:[{3},{4},{5}]\n", firstPos.x, firstPos.y, firstPos.z, secondPos.x, secondPos.y, secondPos.z);

    //  get values at coordinates
    bool first = A.latticeArray[firstPos.x, firstPos.y, firstPos.z];
    bool second = A.latticeArray[secondPos.x,secondPos.y,secondPos.z];

    if (first == second) //don't bother if they are equal states
        return false;

    //  checks the energies in surroundings for an eventual spin switch
    int surrBefore = surroundCheck(ref A, firstPos, first) ; // - surroundCheck(ref A, secondPos, second));
    int surrAfter = surroundCheck(ref A, firstPos, !first) ; // - surroundCheck(ref A, secondPos, !second));

    if (surrAfter < surrBefore) //switch spin states if lower total energy
    {
        A.latticeArray[firstPos.x, firstPos.y, firstPos.z] = !first;
        A.latticeArray[secondPos.x, secondPos.y, secondPos.z] = !second;
        return true;
    }
    else if ((surrAfter == surrBefore) & latticeDistribution(ref rr))   //TEMPORARY
    {
        A.latticeArray[firstPos.x, firstPos.y, firstPos.z] = !first;        //TEMPORARY
        A.latticeArray[secondPos.x, secondPos.y, secondPos.z] = !second;    //TEMPORARY
        return true;
    }
    else
        return false;
} //FIX SWITCH PROBABILITIES

"" . - #.

+4
1

(, 1-10, 25-40, 100-123), . , .

, , , - .

+5

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