Multithreading Program Stalls in Optimized Mode but Runs Normally in -O0
This issue arises from a multithreading program where shared variables are not atomic. Specifically, the problem lies with the boolean variable finished that is accessed by two threads without any synchronization or atomicity.
In the optimized mode, the compiler assumes that shared variables accessed by multiple threads are protected. However, in this program, finished is declared as a regular bool, making it non-atomic. This allows the compiler to optimize out the synchronization mechanisms that are essential for multithreaded operation.
To resolve this issue, finished should be declared as std::atomic
Fixed Code:
#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::cout << "\nmain thread>
Live Demo: coliru
Additional Considerations:
The above is the detailed content of Why Does My Multithreaded Program Stall in Optimized Mode But Work in -O0?. For more information, please follow other related articles on the PHP Chinese website!