Optimized Multithreading Program Stalled in Optimized Mode: Resolution through Atomic Variables
Consider the following multithreading program:
static 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>
This program operates as expected in debug mode or with the -O0 optimization flag. However, when executed in release mode or with optimization flags -O1, -O2, or -O3, it encounters an issue and fails to provide any output.
Cause and Resolution
The source of the problem lies in the simultaneous access to the non-atomic and unguarded variable finished by multiple threads. This variable does not guarantee atomicity, leading to undefined behavior. To rectify this, finished should be defined as an std::atomic This resolves the issue and allows the program to run successfully in optimized mode, displaying the desired output: Significance of std::atomic Atomic variables, such as std::atomic Additional Considerations While using atomic variables significantly improves concurrency safety, it's essential to be aware that optimizations can have far-reaching consequences. For instance, compilers might optimize unprotected variables into registers or eliminate redundant accesses to improve performance. To prevent unintended optimizations, proper variable safeguarding and explicit instructions to the compiler are crucial. The above is the detailed content of Why Does My Optimized Multithreaded Program Stall, and How Can Atomic Variables Fix It?. For more information, please follow other related articles on the PHP Chinese website!static std::atomic<bool> finished = false;
result = 1023045342
main thread>