Using volatile to prevent compiler optimizations

CSharp · Console

/Program.cs

using System;
using System.Threading;
using System.Linq;

public class Program
{
    private static volatile float _readWriteValue = 0;
    private static volatile bool _stop = false;

    public static void Main()
    {
        Timer timer = new(_ => _stop = true);
        timer.Change(200, Timeout.Infinite);

        Thread t1 = new(() => Thread1());
        Thread t2 = new(() => Thread2());

        t1.Start(); t2.Start();
        t1.Join(); t2.Join();
    }

    private static void Thread1()
    {
        Random ran = new Random();
        while (!_stop)
        {
            _readWriteValue = ran.Next(1, 100);
        }
    }

    private static void Thread2()
    {
        while (!_stop)
        {
            const int BUFFER_SIZE = 100;
            float[] bufferData = new float[BUFFER_SIZE];
            for (int i = 0; i < BUFFER_SIZE; i++)
            {
                bufferData[i] = _readWriteValue;
            }
            // Print statistics
            Console.WriteLine($"Distinct values in the buffer: {String.Join(", ", bufferData.Distinct())}");
            Thread.Sleep(10);
        }
    }
}
;