[英]Boost ASIO Async_receive crashing program
For the most part my program runs fine, but occasionally it will crash. 在大多数情况下,我的程序运行良好,但有时会崩溃。 If I pause the program mid run it will also crash.
如果我在运行中暂停程序,它也会崩溃。 Any insight as to why would be greatly appreciated!
关于为什么的任何见解将不胜感激! I think it could be due to async_read_some being called multiple times before it is actually executed.
我认为这可能是由于async_read_some在实际执行之前被多次调用。
Main.cpp: Main.cpp:
while(true)
{
sensor->update();
if (sensor->processNow == 1)
{
sensor->process(4);
sensor->processNow = 0;
sensorReadyForUpdate = 1;
}
}
Constructor: 构造函数:
sensorHandler::sensorHandler(std::string host, int port, std::string name) :
socket_(ioservice_),
sensorAddress_(boost::asio::ip::address::from_string(host), port),
dataRequested_(false),
dataReady_(false)
{
}
Update Function: 更新功能:
bool sensorHandler::update()
{
ioservice_.poll_one();
if (inOperation == false)
{
inOperation = true;
socket_.async_read_some(boost::asio::buffer(receiveBuffer, receiveBuffer.size()), boost::bind(&sensorHandler::receiveCallback, this, _1, _2));
return success;
}
} }
Receive Callback Function: 接收回叫功能:
bool sensorHandler::receiveCallback(const boost::system::error_code& error, std::size_t bytes_transferred)
{
std::cout << "success - in receiveCallBack" << std::endl;
processNow = 1;
inOperation = false;
}
Includes: 包括:
#include "sensorHandler.h"
#include <boost\bind.hpp>
#include <boost\asio\write.hpp>
#include <iostream>
#include <windows.h>
Header File: 头文件:
class sensorHandler
{
public:
sensorHandler(std::string host, int port, std::string name);
~sensorHandler();
bool connect();
bool update();
boost::array<char, 400000> receiveBuffer; // was 50000
}
I may be missing the point of the question, but is the question that you want to run an async operation in a loop? 我可能遗漏了问题的要点,但是您是否想在循环中运行异步操作的问题?
The classical way to achieve that is via call chaining, so in the completion handler you enqueue the next operation: 实现此目标的经典方法是通过调用链接,因此在完成处理程序中,您可以加入下一个操作:
bool IFMHandler::receiveCallback(const boost::system::error_code& error, std::size_t bytes_transferred)
{
/*code to process buffer here - ends with processNow = 1 and inOperation = false*/
if (!error) {
socket_.async_read_some(boost::asio::buffer(receiveBuffer,
receiveBuffer.size()), boost::bind(&IFMHandler::receiveCallback, this, _1, _2));
}
}
So, now you can simply call 所以,现在您可以简单地致电
ioservice_.run();
and the chain will run itself. 连锁店将自行运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.