Given the following code.
int i = 0;
int width = 100;
int height = 100;
int[] output = new int[width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
output[i++] = y+x;
}
}
I can be assured that both the index and the assigned sum are incremental.
With the following code I am splitting the job into several sub-tasks
int width = 100;
int height = 100;
int[] output = new int[width * height];
int partitionCount = this.Parallelism;
Task[] tasks = new Task[partitionCount];
for (int p = 0; p < partitionCount; p++)
{
int current = p;
tasks[p] = Task.Run(() =>
{
int batchSize = height / partitionCount;
int yStart = current * batchSize;
int yEnd = current == partitionCount - 1 ? height : yStart + batchSize;
this.Apply(output, width, height, yStart, yEnd, ref yStart);
});
}
Task.WaitAll(tasks);
void Apply(int[] output, int width, int height, int startY, int endY, ref int index)
{
for (int y = startY; y < endY; y++)
{
for (int x = 0; x < width; x++)
{
// How do I increment the index within output.
// Interlocked.Increment(ref index);
// output[index] = y+x; doesn't work
}
}
}
How can I ensure that the index is incremented appropriately and ensure that the assigned output at each index of the multi-threaded approach matches the single-threaded approach?
Edit: I've added an expected output to further explain what I am trying to do.
e.g.
output[0] = "0+1";
output[1] = "0+1";
output[2] = "0+2";
output[3] = "0+3";