小编ros*_*573的帖子

为什么 clang 会优化轮询另一个线程写入的变量的循环?

当我学习 C++ 时,我发现了一些奇怪的东西......
我认为下面的代码会产生大数的结果(至少不是 1.1)。
相反,结果是在此处输入图像描述

其他编译器按预期工作。
但是具有积极优化的 clang 编译器似乎忽略了 while 循环。
所以我的问题是,我的代码有什么问题?还是clang有意为之?

我使用了apple clang编译器(v14.0.3)

#include <iostream>
#include <thread>


static bool should_terminate = false;

void infinite_loop() {
    long double i = 1.1;
    while(!should_terminate)
        i *= i;
    std::cout << i;
}

int main() {
    std::thread(infinite_loop).detach();
    std::cout << "main thread";
    for (int i = 0 ; i < 5; i++) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << ".";
    }
    should_terminate = true;
}
Run Code Online (Sandbox Code Playgroud)

来自编译器资源管理器的汇编结果(clang v16.0.0,-O3)
这似乎也跳过了 while 循环。

_Z13infinite_loopv:                     # @_Z13infinite_loopv
        sub     rsp, 24 …
Run Code Online (Sandbox Code Playgroud)

c++ optimization multithreading clang data-race

2
推荐指数
1
解决办法
225
查看次数

标签 统计

c++ ×1

clang ×1

data-race ×1

multithreading ×1

optimization ×1