简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM