Home > Backend Development > C++ > Why Does My Multithreaded Program Hang When Compiled with Optimization?

Why Does My Multithreaded Program Hang When Compiled with Optimization?

Linda Hamilton
Release: 2024-12-19 08:24:56
Original
944 people have browsed it

Why Does My Multithreaded Program Hang When Compiled with Optimization?

Multithreading Program Stuck in Optimized Mode

Problem:

A simple multithreading program behaves unexpectedly when compiled in optimized modes. While the program runs normally in debug mode or with -O0, it becomes stuck when compiled with -O1, -O2, or -O3.

Solution:

The issue lies in the non-atomic access to the finished variable. In a multithreaded environment, two threads accessing a non-guarded, non-atomic variable can lead to undefined behavior. To fix this, the finished variable should be made atomic.

Fix:

#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::endl;
    std::cout << "\nmain thread>
Copy after login

Explanation:

By using std::atomic, we ensure that the finished variable is accessed and modified in an atomic manner, preventing race conditions and undefined behavior.

Additional Notes:

  • Using volatile for this purpose is not recommended, as it is not guaranteed to provide the necessary synchronization.
  • The compiler can optimize the execution of code, including variable access patterns. It is important to use appropriate synchronization primitives to ensure correct program behavior.

The above is the detailed content of Why Does My Multithreaded Program Hang When Compiled with Optimization?. 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