首页 > 解决方案 > 为什么 std::atomic_flag 会在这里导致死锁?

问题描述

为什么这个 C++20 的乒乓示例std::atomic_flag经常导致死锁?我正在使用 GCC 11.1 进行编译。

#include <atomic>
#include <iostream>
#include <thread>

constexpr auto count_limit = 10'000;

auto atomic_flag = std::atomic_flag{};
auto counter = std::atomic<int>{};

void ping() {
    while (counter < count_limit) {
        atomic_flag.wait(true);

        ++counter;

        atomic_flag.test_and_set();
        atomic_flag.notify_one();
    }
}

void pong() {
    while (counter < count_limit) {
        atomic_flag.wait(false);
        atomic_flag.clear();
        atomic_flag.notify_one();
    }
}

int main() {
    atomic_flag.test_and_set();

    {
        auto const t1 = std::jthread{ping};
        auto const t2 = std::jthread{pong};
    }

    std::cout << "Finished\n";
}

更新:godbolt.org 上的 Linux 机器上不会出现“死锁”:https ://godbolt.org/z/zPb8d1bca 。它也不会发生在我自己的 Linux 机器上。它确实发生在我的 Windows 机器上,所以这可能是 Windows 特有的 GCC 错误。

标签: c++concurrencyatomicc++20

解决方案


推荐阅读