我使用這樣的代碼在多線程:數學課給出錯誤
古例如:
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);
}
}
但我看到,有時候水庫是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 ;
...
}
}
}
}
有時數學函數給瘋狂的結果。
爲什麼需要鎖定? – Matthew 2012-07-30 14:53:47
@Matthew - 以秒爲單位擊敗我:) – 2012-07-30 14:54:16
你可以發佈測試用例嗎?你使用什麼多線程方法? – Darek 2012-07-30 14:57:13