Multithreading Program Optimization Woes
In your code, you have a multithreaded program where a separate thread increments a counter while the main thread waits for a second and then sets a flag to signal the counter thread to stop. However, when running in optimized mode (-O1 -O3), the program gets stuck without printing any output.
The Culprit: Non-Atomic Variable Access
The issue arises from the "finished" variable, which is a simple bool that is accessed concurrently by multiple threads without any synchronization or atomicity guarantees. When accessed concurrently, this variable can lead to undefined behavior (UB).
Solution: Use std::atomic
To address this, the "finished" variable should be declared as an atomic type, such as std::atomic
Revised 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>
Explanation:
In the revised code, the "finished" variable is declared as std::atomic
Note on Optimization
In optimized mode, the compiler may perform aggressive optimizations that can cause issues if data is not properly synchronized. By using std::atomic, you explicitly instruct the compiler to maintain the atomicity of the "finished" variable, even in optimized builds.
The above is the detailed content of Why Does My Optimized Multithreaded Program Freeze When Using a Non-Atomic Boolean Flag?. For more information, please follow other related articles on the PHP Chinese website!