I have a method which just increases an Integer Value (i++)
public void Calculate()
{
for(int i=0;i<1500;i++)
y++;
}
Where Y is Int Class Variable .
Thread thr1 = new Thread(Calculate);
thr1.Start();
Thread thr2 = new Thread(Calculate);
thr2.Start();
Thread thr3 = new Thread(Calculate);
thr3.Start();
Thread thr4 = new Thread(Calculate);
thr4.Start();
By starting 4 Threads with Calculate Delegate ,the Y Value should be 6000 ,if Y starts with Value 0
But not always it became 6000 ,Sometimes im getting 5993 or 6003 so there are cases where this value is not the one which Logically should be .
So is there any solution to prevent from that ,i dont want to Block Y while a thread is increasing ,so is there a way to set Variable Value Parallel from Multiply Threads ?
EDIT : It is working with Interlock.Increment(); but it slows down the Algorithm ,so what is doing it correct and faster is :
int i = 0;
int j = 0;
for (i = 0; i < 1500; i++)
{
j++;
this.label1.Text = y.ToString();
}
lock(y)
{
y += j;
}
This is a race condition. You need to use Interlocked.Increment to do this in a threadsafe manner.