Unfortunately the compiler can not fix any race conditions for you. When turning on optimizations the execution time of your code part changes. This can result that the race condition is less or more visible. Depending on your CPU and other programs you are running. Seeing correct runs are in your case happening on accident.