Problem:
A simple multithreading program behaves unexpectedly when compiled in optimized modes. While the program runs normally in debug mode or with -O0, it becomes stuck when compiled with -O1, -O2, or -O3.
Solution:
The issue lies in the non-atomic access to the finished variable. In a multithreaded environment, two threads accessing a non-guarded, non-atomic variable can lead to undefined behavior. To fix this, the finished variable should be made atomic.
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)); finished = true; std::cout << "result = " << result.get() << std::endl; std::cout << "\nmain thread>
Explanation:
By using std::atomic
Additional Notes:
The above is the detailed content of Why Does My Multithreaded Program Hang When Compiled with Optimization?. For more information, please follow other related articles on the PHP Chinese website!