All that I read about volatile says that it is never safe, but I still feel inclined to try it, and I did not see that this particular scenario was declared unsafe.
I have a separate stream that displays the scene, pulling data from the main modeling stream. It does not sync and works fine.
The problem is that when the program exits the system, then the visualizer must stop pulling data from the modeling stream before the modeling stream can safely clear itself, without forcing the rendering to try to read invalid memory.
To accomplish this, I have a visualization tool endlessly in my stream:
volatile bool stillRendering; void RenderThreadFunction() { stillRendering = true; while(programRunning) { renderer->render(); } stillRendering = false; }
In the main thread of the program, when the windproc exit message is received, I:
void OnQuit() { programRunning = false; while(stillRendering) { } delete application; }
The goal is to ensure that the visualizer stops retrieving data from the application before calling delete in the application.
At first I tried this without any volatile keywords, and it worked in debug mode, but in release mode it hung. I assume the compiler has done some optimization, which causes the program to stop checking the stillRendering value.
Adding volatility to a simple display that caused the application to complete successfully when I tested it so far. I am not sure why this does not matter if "programRunning" is unstable.
Finally, I do not know how the use of volatile for "stillRendering" will affect program performance. It doesn't matter to me if doing stillRendering volatile affects the performance of OnQuit (), but to me it matters if it affects the performance of RenderThreadFunction ()
c ++ multithreading thread-safety volatile boolean
Matt swarthout
source share