Home > Backend Development > C++ > Why Does My Optimized Multithreaded Program Freeze When Using a Non-Atomic Boolean Flag?

Why Does My Optimized Multithreaded Program Freeze When Using a Non-Atomic Boolean Flag?

Barbara Streisand
Release: 2024-12-28 00:33:19
Original
311 people have browsed it

Why Does My Optimized Multithreaded Program Freeze When Using a Non-Atomic Boolean Flag?

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. std::atomic provides atomicity guarantees, ensuring that access to the variable is synchronized and well-defined.

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>
Copy after login

Explanation:

In the revised code, the "finished" variable is declared as std::atomic, ensuring atomic access. This prevents the undefined behavior that was causing the program to freeze.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template