多个线程同时对一个变量进行++操作是不是安全
总值不论是否采取同步,都是不会变的,但是实际应用中常常不只求总值,还有对全局变量的判断和使用,比如第一个线程当i++循环两次时,输出i=2。虽然第一个线程代码中确实循环两次,i从0加到2;但在没有同步的情况下另一线程也在对i加1,所以原本输出i=2的地方可能输出i=3,4....从而造成不一致性。
以下是加lock代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Data;
public class LockMe
{
}
public class pp
{
private int i = 0;
private LockMe l=new LockMe();
public void plus1()
{
lock(this.l)
{
for (int j = 0; j < 3; j++)
i++;
}
}
public void plus2()
{
lock (this.l)
{
for (int j = 0; j < 3; j++)
i++;
}
}
}
public class PP
{
static void Main()
{
pp p = new pp();
ThreadStart t1 = new ThreadStart(p.plus1);
ThreadStart t2 = new ThreadStart(p.plus2);
Thread T1 = new Thread(t1);
Thread T2 = new Thread(t2);
T1.Start();
T2.Start();
Console.WriteLine(p.i);
}
}
收起
阅读全文