Take this program as an example:
class Program
{
public static double myVar1 = 0;
public static double myVar2 = 0;
static void Main()
{
Thread thread1 = new Thread(new ThreadStart(update_variable));
thread1.Start();
while (true)
{
myVar2 = myVar1;
}
}
static update_variable()
{
while (true)
{
myVar1 = 2222222.22;
myVar1 = 1111111.11;
}
}
}
Would it ever be possible for myVar2 to equal a value other than 222222.22 or 1111111.11? In other words, are the bytes for a variable changed "all or nothing" or could the main thread see myVar1 at a instance in time when some of the bytes have changed and others have not, giving an unexpected value?
I've tested the above program and do NOT see that behavior, but wondering if it's possible and if this would be considered thread safe code. I would prefer to not use the resources of a lock since I have only one thread that changes the data and one that uses the data.