Seeing is believing. Can anyone reproduce a program that reads a torn decimal? I tried spinning up multiple threads changing the same decimal between 1 and 2. I did not catch any reads different from 1 or 2.
I like to see that a reader thread does not see a atomic change from a writer thread, so the value should be something different from 1 or 2.
void TornDecimalReadTest()
{
decimal sharedDecimal = 1;
int threadCount = 100;
var threads = new List<Thread>();
for (int i = 0; i < threadCount; i++)
{
int threadId = i;
var thread = new Thread(() =>
{
Thread.Sleep(5000);
decimal newValue = threadId % 2 == 0 ? 1 : 2;
bool isWriterThread = threadId % 2 == 0;
Console.WriteLine("Writer : " + isWriterThread +
" - will set value " + newValue);
for (int j = 0; j < 1000000; j++)
{
if (isWriterThread)
sharedDecimal = newValue;
decimal decimalRead = sharedDecimal;
if (decimalRead != 1 && decimalRead != 2)
Console.WriteLine(decimalRead);
}
});
threads.Add(thread);
}
threads.ForEach(x => x.Start());
threads.ForEach(x => x.Join());
}