Volatile variables

If You want to exit from loop if some bool set from another thread You may be victimed by compiler’s code optimalization.

class Test
{
    private bool _loop = true;

    public static void Main()
    {
        Test test1 = new Test();

        // Set _loop to false on another thread
        new Thread(() => { test1._loop = false;}).Start();

        // Poll the _loop field until it is set to false
        while (test1._loop == true) ;

        // The loop above will never terminate!
    }
}

Found here: http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/

This entry was tagged , .

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.