A
A
Alexey Smirnov2017-10-27 00:27:09
.NET
Alexey Smirnov, 2017-10-27 00:27:09

How to parallelize the execution of the "For" loop?

Hello.
I used a loop forto write a two-dimensional string array in Excel:

for (var column = 1; column <= columns; column++)
{
    // Тело цикла, выполняющее функцию записи одного столбца в Excel документ.
}

After that, I decided to speed up the process of writing data to Excel by running the loop in parallel for:
Parallel.For(1, columns + 1, column =>
{
    // Тело цикла, выполняющее функцию записи одного столбца в Excel документ.               
});

Due to this, the recording time decreased by an average of 16%.
But there is one problem. When I write data to Excel for the first time (after restarting the computer), they are in the correct order in the Excel document. But as soon as I restart the program, the columns in the new, just written document, begin to arrange themselves chaotically. After I restart the computer again and run the program again, the data is again written to Excel in the correct order.
PS I have restarted the computer 6 times, and every time after the restart the data was correctly recorded in Excel. But as soon as I re-ran the program, the data was written to Excel in random order.
PPS When using a normal cycle for, this problem does not arise.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cicatrix, 2017-10-27
@ERAFY

Race Condition apparently. Welcome to the world of multithreading. With parallel execution, there is no guarantee that the order will be preserved. Whoever got up first, that and slippers.
I would advise you to break the array (or whatever you have in the loop) into 2, 3 ... N parts, strictly assigning each part its own areas (say, the first thread fills columns 1 ... 10, the second - 11..20 etc.) and run N synchronous loops on different threads.
And in principle, in order to understand how multithreading works, I would first try to do everything manually, using the good old System.Threading.Thread. In Tasks, a lot is hidden "under the hood", and you can step on a lot of rakes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question