std::<bool>atomic和lambda
std::atomic<bool> and 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
。
这会导致未定义的行为;程序的任何行为都可以被标准接受。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何从 std::atomic 中提取指针 T<T>?
- 可组合的lambda/std::函数与std::可选
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- std::memory_order for std::atomic:<T>:wait
- 如何将lambda作为模板类的成员函数参数
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 在 lambda 捕获中声明的变量的类型推导
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 模板函数指针和lambda
- 两组使用lambda函数的大括号
- 使lambda不可复制/不可移动
- FLTK:按下哪个按钮 - 将数字传递给按钮的回调 (lambda)
- MESI协议和std::atomic-它是否确保所有写入立即对其他线程可见?
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 在 lambda 表达式中使用 std::atomic
- std::<bool>atomic和lambda