有谁知道为什么这个程序进入无限循环,而不是在 5 秒左右后停止?
最新的 gcc 和 clang 编译器都会发生这种情况;是否atomic_bool
遭受与向量相同的问题bool
?
如果我使用atomic<int>
它可以正常工作。
#include <algorithm>
#include <memory>
#include <utility>
#include <iostream>
#include <vector>
#include <functional>
#include <future>
#include <chrono>
using namespace std;
using namespace chrono_literals;
void send_heart_beat()
{
cout << "sending heartbeat" << endl;
}
std::future<void> f;
int main()
{
std::atomic<bool> stop(false);
f = std::async(std::launch::async,[&stop]() { while(!stop) { send_heart_beat(); std::this_thread::sleep_for(1s); } });
std::this_thread::sleep_for(5s);
stop = true;
}