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

后端 未结 5 1622
醉话见心
醉话见心 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

    If you want your code to work on all architectures in all compilers, use C++11 atomics:

    std::atomic stillRendering;
    
    void RenderThreadFunction()
    {
        stillRendering = true;
    
        while(programRunning)
        {
            renderer->render();
        }
    
        stillRendering = false;
    }
    

    Volatile is not designed for use with multi-threading -- compilers are actually allowed by the standard to reorder volatile accesses with non-volatile accesses. VC++ extends volatile's feature set to prevent reordering, but other compilers do not, and it might break on those compilers.

    As others have mentioned, volatile also doesn't affect visibility, meaning architectures which aren't cache-coherent may never see the flag set. x86 isn't even immediately cache-coherent (writes would be extremely slow), so your program will invariably end up looping more than it should while the write is sent through various buffers.

    C++11 atomics avoid both of these problems.

    OK, so this was mainly meant to correct your current code and warn you off of misusing volatile. James' suggestion of using a condition variable (which is merely a more efficient version of what you're doing) is probably the best actual solution for you.

提交回复
热议问题