Is this (volatile bool) always thread safe?

Aidiakapi picture Aidiakapi · Jan 8, 2012 · Viewed 14.6k times · Source

I'm wondering if this is completely thread-safe and whether or not the volatile keyword should be in place.

using System.Threading;

class Program
{
    private static volatile bool _restart = true;

    private static void Main()
    {
        while (_restart)
        {
            // Do stuff here every time for as long as _restart is true
            Thread.Sleep(1);
        }
    }

    private static void SomeOtherThread()
    {
        Thread.Sleep(1000);
        _restart = false;
    }
}

I think it is, but I want to double check, since I'm not 100% certain I just want to be sure.

I think the volatile keyword is required because then it would never be possible to have the value cached in registers or alike optimizations.

Answer

Mike Nakis picture Mike Nakis · Jan 8, 2012

What SLaks answered is correct, of course, but to answer your question: yes on both counts: it is safe, it should be declared volatile.