1

有谁知道为什么这个程序进入无限循环,而不是在 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;
}
4

1 回答 1

1
 std::atomic<bool> stop(false);
 std::future<void> f;

这两个变量在不同的范围内,并且f' 的范围比 ' 的范围寿命更长stop

f = std::async(std::launch::async,[&stop]() { while(!stop) { send_heart_beat(); std::this_thread::sleep_for(1s); } });

在这里,我们将一个引用绑定stop到一个 lambda,然后将该 lambda 的一个(副本)存储到一个asyncf.

f超出范围时,其析构函数等待异步任务完成。但是因为f's 的作用域比stop's 更持久,所以我们离开stopbefore的作用域f等待线程完成。

因此,我们的线程在不再存在stop后通过悬空引用继续访问。stop

这会导致未定义的行为;您的程序的任何行为都是标准可以接受的。

于 2018-01-04T16:37:32.563 回答