Safe to use volatile bool to force another thread to wait? (C++)

后端 未结 5 1632
醉话见心
醉话见心 2021-02-08 18:52

Everything I\'ve read about volatile says it\'s never safe, but I still feel inclined to try it, and I haven\'t seen this specific scenario declared unsafe.

I have a sep

5条回答
  •  青春惊慌失措
    2021-02-08 19:09

    Adding volatile to just stillRendering caused the application to successfully exit everytime I've tested it

    Yes, your scenario will work.

    The common mistake that occurs when using volatile variables for thread synchronization is when operations on volatile variables are presumed to be atomic. They aren't.

    In your case, you are polling a single bool waiting for it to change exactly once to exactly 0. You don't seem to be expecting any operation to be atomic. On the other hand, even if you were polling a single int, C++ will not guarantee that a thread changing that int will do so atomically.

    I'm not certain why it doesn't seem to matter if "programRunning" is volatile.

    It does matter. Make it volatile.

    Making a variable volatile will guarantee that specific cache optimizations are avoided, which is what you want.

    That doesn't mean that you are guaranteed those same cache optimizations when a variable isn't volatile. You're simply letting the compiler decide. And at this particular time, the compiler happens to be making a decision that works for you.

    Lastly, I am uncertain how the performance of the program will be impacted by using volatile for "stillRendering".

    Your performance will likely be negatively affected by this:

    while(stillRendering)
    {
    }
    

    You are asking one thread (perhaps one entire CPU core) to endlessly, without rest, read a single variable.

    Consider adding a sleep call in that while loop.

提交回复
热议问题