std::<bool>atomic和lambda



有人知道为什么这个程序进入无限循环,而不是在 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;
}
 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 的(副本(存储到由 f 管理的 async 对象中。

f超出范围时,其析构函数将等待异步任务完成。 但是由于f的作用域比stop的作用域更持久,因此我们在等待线程完成之前f离开stop的范围。

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

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

最新更新