Can multiple threads write safely to different array indices without synchronization? #118954
-
Hi, suppose there is this code sample: object[] objects = new object[2];
_ = Parallel.For(fromInclusive: 0, toExclusive: 2, (i) => { // This is specially crafted so that threads do write to the same array locations.
objects[i] = new object();
});
Console.WriteLine($"{objects[0]} {objects[1]}"); // Access the array (in any way really). Now I would expect that one needs to change it to object lockObj = new();
object[] objects = new object[2];
_ = Parallel.For(fromInclusive: 0, toExclusive: 2, (i) => {
lock (lockObj)
{
objects[i] = new object();
}
});
lock (lockObj)
{
Console.WriteLine($"{objects[0]} {objects[1]}");
} to be sure that:
Is the first sample correct or not? Thank you PS: I know that the memory model for .NET application is described1 but I don't understand it fully (yet). Footnotes |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
I'm not sure I understand what is the expected behavior here, but Parallel.For is blocking so all array elements will be initialized as is, lock here makes no sense. |
Beta Was this translation helpful? Give feedback.
-
This is one of the "traditional" (As in, across multiple languages) ways that multi-threaded work has been done safely - have multiple threads work on separate array elements, then do something with the combined results afterwards. |
Beta Was this translation helpful? Give feedback.
Parallel.For(..)
is going to have to callWait(..)
/Join(..)
or similar in order to be able to complete the call, which will use barriers.This is one of the "traditional" (As in, across multiple languages) ways that multi-threaded work has been done safely - have multiple threads work on separate array elements, then do something with the combined results afterwards.