如何使用lambda来boost异步完成处理程序
How to use lambda to for boost asio async completion handler
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
void print(boost::asio::deadline_timer* t, int* count)
{
if (*count < 5)
{
std::cout << *count << "n";
++(*count);
t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
t->async_wait(boost::bind(print, t, count));
}
}
int main()
{
boost::asio::io_service io;
int count = 0;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
// t.async_wait(boost::bind(print, &t, &count));
t.async_wait([&]{ // compile error occurred
print(&t, &count);
});
io.run();
std::cout << "Final count is " << count << "n";
return 0;
}
bind和lambda exp有什么不同?我想这在语法上是可以的,问题是async_wait需要一个参数为const boost::system::error_code&e"。
我不太了解asio,但是添加请求的参数可以解决这个问题。
t.async_wait([&] ( const boost::system::error_code& ) {
print(&t, &count);
});
这看起来像是Boost的一个怪癖或bug。Bind允许对从函数指针生成的绑定表达式使用附加的、被忽略的参数。最好不要依赖它,而是显式地接受并丢弃错误代码。
相关文章:
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 为什么我的 IExtractIcon 处理程序没有被调用?
- 在遍历处理程序的向量时注册和注销处理程序
- 有可能在信号处理程序中设置promise吗
- 在信号处理程序中捕获C++未处理的异常并恢复应用程序
- 通过安装信号处理程序关闭多线程应用程序
- QDateTime::toString() 在退出处理程序中使用时失败
- 如何在 WindowProc 处理程序中区分箭头键和数字键盘?
- async_write完成处理程序最早何时完成?
- C++事件系统 - 多态事件和事件处理程序
- 具有shared_ptr的处理程序中的分段错误
- 为什么我的信号处理程序只执行一次?
- GTK C++:找不到信号处理程序 您是否使用 -rdynamic 进行了编译?
- 如何使用从处理程序调度的最终回调将响应异步返回给调用方on_read?
- C++ 在信号处理程序后继续执行
- wxWidgets 拖放文件事件处理程序初始化问题(无效static_cast)
- 某些 boost::asio 异步函数是否将处理程序连接到操作,以便处理程序被触发一次?
- 没有信号处理程序的POSIX定时器的目的是什么?
- 处理程序的模块列表中有一个错误的模块"WebSocketModule"