为什么 std::atomic_flag 会在这里导致死锁?

时间:2021-06-11 09:35:40

标签: c++ concurrency atomic c++20

为什么这个带有 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 错误。

0 个答案:

没有答案
相关问题