Reputation: 185
I am trying to understand the more lower level operations of the TPL and was wondering how a parallel for handles data locking, e.g. Performing a calculations over a 2D array. I ve been going around in circles on MSDN and haven't been able to find a detailed explanation. Any suggestions?
Upvotes: 1
Views: 269
Reputation: 4094
I'll post a gross oversimplification to paint the picture in code; post this into a console app and it'll spit out the data and which thread is working on it. You can update this to work with your own data to make it more relevant.
var list = new List<int>(64);
for (var i = 1; i <= 64; i++)
{
list.Add(i);
}
var result = Parallel.ForEach(list, entry =>
{
var line = string.Format("Thread ID {0} is listing entry {1}", Thread.CurrentThread.ManagedThreadId, entry);
Console.WriteLine(line);
});
while (!result.IsCompleted)
{
Thread.Sleep(50);
}
Console.ReadKey();
Upvotes: 0
Reputation: 12077
If you access/modify shared mutable state in the body of the for loop, synchronizing that access is up to you.
Upvotes: 1
Reputation: 203817
It doesn't need any locking because there is never any situation in which multiple threads are accessing the same locations in memory. There is a single thread that is scheduling work for the workers, cutting out sections of the work to be done and giving them out. Because there is only one thread doing this, it doesn't need to synchronize with anyone else. None of the workers (should be) working on shared data.
Upvotes: 0