2

我在多线程中使用这样的代码:

老例子:

  class All
     {
        object lockAll = new object();
        public All ()
        {
           lock(lockAll)
           {
               double res= Magnitude(1d, 0.1d , 0.2d);
           }
        }
        private double Magnitude(double X, double Y, double Z)
        {
           return Math.Sqrt(X * X + Y * Y + Z * Z);
        }
     }

但我看到有时 res 是 1.3 * 10 ^-314。为什么???全部被锁定。:真实代码的一部分:

class PointSensors : IDisposable
    {
object lockAcs = new object(); //Can it be non static? I think yes
object lockMag = new object();
// When i got info from sensors. Multitheading method called many times every time in new thread
 public void OnSensorChanged(SensorEvent ev)
        {
            Sensor curS = ev.Sensor;
            long timeStamp = ev.Timestamp;
              // Vector from sensors
             Vector3 vector = new Vector3(ev.Values[0], ev.Values[1], ev.Values[2]);
                if (curS.Type == SensorType.Accelerometer)
                {
                    lock (lockAcs)
                    {
                       double TotalAcseleration = vector.Magnitude - 9.8d;
                       ...
                    }
                }

                if (curS.Type == SensorType.MagneticField))
                {
                    lock (lockMag)
                    {
                       double TotalMagVect = vector.Magnitude ;
                       ...
                    }
                }


        }
}

有时数学函数会给出疯狂的结果。

4

2 回答 2

4

您的锁没有意义,因为res它不是共享变量。它的作用域只存在于锁中,因此无论如何其他线程都无法访问它。

于 2012-07-30T14:54:46.707 回答
3

因为您锁定不同的实例。使您的锁成为静态的。

class All
 {
    private static object lockAll = new object();
    public All ()
    {
       lock(lockAll)
       {
           double res= Magnitude(1d, 0.1d , 0.2d);
       }
    }
    private double Magnitude(double X, double Y, double Z)
    {
       return Math.Sqrt(X * X + Y * Y + Z * Z);
    }
 }
于 2012-07-30T14:55:18.613 回答