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
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.