Home > Backend Development > C++ > Why Does My Multithreaded Program Stall in Optimized Mode But Work in -O0?

Why Does My Multithreaded Program Stall in Optimized Mode But Work in -O0?

Patricia Arquette
Release: 2024-12-29 22:02:30
Original
650 people have browsed it

Why Does My Multithreaded Program Stall in Optimized Mode But Work in -O0?

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. This type provides atomic read and write operations, ensuring that concurrent accesses to the variable remain well-defined and consistent.

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

Live Demo: coliru

Additional Considerations:

  • Volatile variables alone cannot guarantee atomicity. While they prevent the compiler from optimizing away read/write operations, they do not provide memory barriers or synchronization primitives.
  • Modern compilers are highly aggressive in optimization. It is important to explicitly indicate shared memory regions and resource synchronization requirements to prevent unexpected behavior.

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!

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