gpt4 book ai didi

c++ - Boost ASIO,不调用 async_read_some 回调

转载 作者:行者123 更新时间:2023-11-30 02:33:07 27 4
gpt4 key购买 nike

我的代码适用于 read_some,但不适用于 async_read_some。我正在读取的数据长度为 5 个字符,而 MAX_RESPONSE_SIZE 256。打开端口后,我从 main 中调用了一次 async_read_some,但在我刷了几次代理卡后,回调从未被调用过。我尝试在 async_read_some 之后添加 io_service.run() 但它没有帮助。我错过了什么吗?谢谢。

标题

boost::system::error_code error;
boost::asio::io_service io_service;
typedef boost::shared_ptr<boost::asio::serial_port> serial_port_ptr;
serial_port_ptr serial_port;
char read_buffer[MAX_RESPONSE_SIZE];

打开

serial_port.reset();
serial_port = serial_port_ptr(new boost::asio::serial_port(io_service));
serial_port->open(device_path, error);

serial_port->set_option(boost::asio::serial_port_base::baud_rate(baud_rate));
serial_port->set_option(boost::asio::serial_port_base::character_size(8));
serial_port->set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
serial_port->set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
serial_port->set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none));

boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));

阅读

serial_port->async_read_some(
boost::asio::buffer(read_buffer, MAX_RESPONSE_SIZE),
boost::bind(
&serial_comm::data_received,
this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);

回调

void serial_comm::data_received(const boost::system::error_code& error, size_t bytes_transferred)
{
// do stuff
}

最佳答案

您必须确保始终有工作要做,以便 io_service::run() 不会返回并完成它正在运行的线程。

如评论中所述,您可以创建一个 io_service::work。但是,我认为这是人为的,是设计问题的征兆。

可能更好的答案是,在 data_received 处理程序中,如果没有发生 fatal error ,您应该准备下一次读取

void serial_comm::data_received(
const boost::system::error_code& error,
size_t bytes_transferred)
{
// do stuff

if( any_kind_of_fatal_error )
{
// return without setting up the next read
// this will end reading
return;
}

// the last read was successful
// so setup for the next
serial_port->async_read_some(
boost::asio::buffer(read_buffer, MAX_RESPONSE_SIZE),
boost::bind(
&serial_comm::data_received,
this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);

}

关于c++ - Boost ASIO,不调用 async_read_some 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35784538/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com