A race condition is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time, but because of the nature of the device or system, the operations must be done in the proper sequence to be done correctly.
Question:How to maintain consistency in a variable that is shared among several threads in Task parallel library?
Description:I am using task parallel library to run a for loop on all of my CPU cores, but I am just thinking that the resultant of all the operation performed is not going to be what I want? Is there a way to perform operations on a class level variable shared with multiple threads so that the answer of Parallel.For() doesn't return inconsistent value! For learning purpose I have written a simple code chunk as follows which is always returning less than 10000000 int total = 0; Parallel.For(0, 10000000, (i) => { total++; }); Console.WriteLine(total); Console.ReadKey();
Posted by: Peter Andre | Posted on: Mar 15, 2019