I'm trying to understand the benefits of a parallel task library using traditional multithreading, and when I think of the situation below, I get stuck thinking that it handles the race condition or do we need to deal with this in our code?
Here is my code:
int depdt = 0; Parallel.For(1, 10, mem => { for (int dep = 1; dep <= 10; dep++) { depdt = dep; Console.WriteLine("MEMBER: " + mem + " " + "Dependent: " + dep); } Console.WriteLine("Dep Value: " + depdt + " " + "mem: " + mem); }); Console.ReadKey();
I ran it a couple of times, and I do not see any thread interfering / overwriting the variable "depdt". But I need to confirm this. (or) To make it thread safe, I have to manually create an instance of the class and implement it as the code below to avoid race conditions.
int depdt = 0; Parallel.For(1, 10, mem => { Worker worker = new Worker(); worker.DoWork(mem); }); Console.ReadKey(); public class Worker { public void DoWork(int mem) { int depdt = 0; for (int dep = 1; dep <= 10; dep++) { depdt = dep; Console.WriteLine("MEMBER: " + mem + " " + "Dependent: " + dep); } Console.WriteLine("Dep Value: " + depdt +" "+ "mem: "+ mem); } }
Reply on @yms: I mean that when using regular threads, varaible depdt becomes unreliable. Here is my code:
for (int mem = 1; mem <= 10; mem++) { var t= new Thread(state => { for (int dep = 1; dep <= 10; dep++) { depdt = dep; Console.WriteLine("MEMBER: " + mem + " " + "Dependent: " + dep); } Console.WriteLine("Dep Value: " + depdt + " " + "mem: " + mem); }); t.Start(string.Format("Thread{0}", mem)); } Console.ReadKey();
Here is my output screen: Infact and mem and dep variables have become unreliable

marak source share