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