According to the Joe Albahari's book Threading in C# reading and writing a field having a size less than or equal to 32 bits is an atomic operation: this implies that in such a scenario it's not possible ending up with a torn read (here you can find a simple way to reproduce a torn read by using a decimal field).
Given that, consider the following C# console application:
using System;
using System.Threading;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
var obj = new Test();
var random = new Random();
var thread1 = new Thread(() =>
{
while (true)
{
Console.WriteLine($"The boolean value is {obj.field}");
}
});
var thread2 = new Thread(() =>
{
while (true)
{
obj.field = (random.Next() % 2) == 0;
}
});
thread1.Start();
thread2.Start();
}
}
class Test
{
public bool field;
}
}
My question is: when I run such a program, what exactly happens in the memory address containing the value of the field being written and read concurrently by the two threads ? Is it possible to corrupt its value doing so ?
Based on my understanding, there is a concurrent access to the same memory address at the same time:
- can I get any kind of runtime exception doing so ?
- is the underlying processor able to handle such a scenario without errors ?
Putting the question in a more general way: when two threads concurrently read and write a 32 bits value the only possible issue is that there is no guarantee about the value being read (I mean that the value read is completely indeterminate due to the concurrent write operation) ?