Is the assignement of a value type considered to be atomic in .Net?
For example, consider the following program:
struct Vector3
{
public float X { get; private set; }
public float Y { get; private set; }
public float Z { get; private set; }
public Vector3(float x, float y, float z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
public Vector3 Clone()
{
return new Vector3(X, Y, Z);
}
public override String ToString()
{
return "(" + X + "," + Y + "," + Z + ")";
}
}
class Program
{
private static Vector3 pos = new Vector3(0,0,0);
private static void ReaderThread()
{
for (int i = 0; i < int.MaxValue; i++)
{
Vector3 v = pos;
Console.WriteLine(v.ToString());
Thread.Sleep(200);
}
}
private static void WriterThread()
{
for (int i = 1; i < int.MaxValue; i++)
{
pos = new Vector3(i, i, i);
Thread.Sleep(200);
}
}
static void Main(string[] args)
{
Thread w = new Thread(WriterThread);
Thread r = new Thread(ReaderThread);
w.Start();
r.Start();
}
}
Can a program like this suffer from a High-Level data race? Or even a Data Race?
What I want to know here is: is there any possibility that v will either contain:
- Garbage values due to a possible data race
- Mixed components X, Y or Z that refer to both pos before assignement and pos after assignment. For example, if pos = (1,1,1) and then pos is assigned the new value of (2,2,2) can v = (1,2,2)?