从线程增加Int时的竞争条件

Bur*_*imi 1 c# int multithreading

我有一个只增加整数值的方法(i ++)

public void Calculate()
{
for(int i=0;i<1500;i++)
 y++;
}
Run Code Online (Sandbox Code Playgroud)

其中Y是Int类变量.

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();
Run Code Online (Sandbox Code Playgroud)

通过使用Calculate Delegate启动4个线程,Y值应该是6000,如果Y以值0开始但是并不总是变为6000,有时我得到5993或6003所以有时这个值不是逻辑应该的值.那么是否有任何解决方案可以防止这种情况,我不希望在线程增加时阻塞Y,那么有没有办法从Multiply Threads设置变量值并行?

编辑:它正在使用,Interlock.Increment();但它减慢了算法,所以正确和更快的做法是:

int i = 0;
int j = 0;
for (i = 0; i < 1500; i++)
{
j++;
this.label1.Text = y.ToString();
}
lock(y)
{
    y += j;
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*lle 9

这是竞争条件.您需要使用Interlocked.Increment以线程安全的方式执行此操作.