I'm new to this concept, but I heard that there are some sort of thread dangers. That said, how can I code this loop in parallel?
//OceanVertexIndexes is List<int>
//trisWithVertex is List<int>[]
foreach (int coord in terrainFace.OceanVertexIndexes)
for (int j = 0; j < trisWithVertex[coord].Count; ++j)//trianglesWith this particular vertex
{
int value = trisWithVertex[coord][j];
int remainder = value % 3;
trianglesDisabled[value - remainder] = true;
trianglesDisabled[value - remainder + 1] = true;
trianglesDisabled[value - remainder + 2] = true;
}
The oceanVertexIndexes is a pretty long enumerable, it has from a few hundreds to a few thousands elements. Also, there is a chance that trianglesDisabled would be accesed at the same time. How should I go about optimising this loop? Spliting it in half? Or is this a case where I can't perform this loop in parallel at all?
//Should I do it like this?
Parallel.Invoke(/*()=>first half of the oceanVertexIndexes loop, ()=>second half*/);
//Or like this?
Parallel.ForEach(terrainFace.OceanVertexIndexes, coord =>
{
for (int j = 0; j < trisWithVertex[coord].Count; ++j)
{
int value = trisWithVertex[coord][j];
int remainder = value % 3;
trianglesDisabled[value - remainder] = true;
trianglesDisabled[value - remainder + 1] = true;
trianglesDisabled[value - remainder + 2] = true;
}
});
It is not possible to know the answer to your question without knowing more about your data and your app logic. Most important: can trisWithVertex[coord]
contain same values for different values of coord
? If yes, then you can have a race condition while accessing trianglesDisabled
. But, since you always set trianglesDisabled
to the same value, true
, the race condition is a non-issue. But, again, what happens in the indexer setter of trianglesDisabled
? Is it just a simple array, or is it a complex class you implemented, with some logic running every time you change a value?
It is also not clear how much benefit you will get from parallelization. You need to benchmark your code to be sure.