Multithreading program stuck in optimized mode but runs normally in -O0
Two threads, accessing a non-atomic, non-guarded variable are U.B. This concerns finished. You could make finished of type std::atomic<bool> to fix this. My fix: #include <iostream> #include <future> #include <atomic> static std::atomic<bool> finished = false; int func() { size_t i = 0; while (!finished) ++i; return i; } int main() { auto result=std::async(std::launch::async, func); std::this_thread::sleep_for(std::chrono::seconds(1)); … Read more