c++ - 为什么 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 错误。
解决方案
推荐阅读
- vba - 从 Access VBA 在 SQL 中保存 jpg
- wordpress - 删除分页的最后一页
- sql - “SELECT TOP”查询的意外 SQL 行为
- python - 填充颜色不适用于我的函数(Python 乌龟图形)
- unix - Ocaml 客户端-服务器:客户端在尝试连接时返回 EAGAIN
- mysql - 更新 MySQL 中 2 个表之间的电子邮件匹配 - 黑名单
- javascript - NextJS - 导出被破坏(没有 CSS,没有 JS)
- c++ - 用于透视的倒置几何 gBuffer 位置。正字法好吗?
- python - 蟒蛇 | 制作列表的百分比
- bluetooth - 与 Arduino 的 GPS 通信