henrikl
henrikl

Reputation: 561

Asio async_read blocking when called inside it's handler

I'm testing a little protocol design of mine and having trouble getting a continuous async_read to work. My idea was to create a generic read handler that outputs the received data (testing) and then checks it to perform protocol-defined actions.

This means that I am calling a new async_read from within this generic handler, which for some reason blocks and my handler never returns, blocking further execution of my program.

The relevant code

void handle_read_server(const asio::error_code&error_code, size_t bytes_transferred, void *adress)
{
    // [...]
    char HELO[4] = {'H','E','L','O'};
    if (*received.data() == *HELO)
    {
        cout << "[Protocol] got HELO";
        got_helo = true;
        short code_data;
        asio::async_read(socket_server, asio::buffer(&code_data, 2), asio::transfer_all(), std::bind(handle_read_server, placeholders::_1, placeholders::_2, &code_data)); // This read is blocking my program to continue it's execution.
    }
}

What I'm asking

What is causing the function to block here? Is there anything I can do appart from having an async_read thread run all the time passing any received values to a stream in the server?

Upvotes: 2

Views: 903

Answers (1)

sehe
sehe

Reputation: 392833

The async_* call does, in fact, not block.

You have Undefined Behaviour, by passing the address of a local variable into the async operation/completion handler.

You have to ensure the buffer's lifetime extends till after the completion. The natural way to achieve that would be to make the buffer a member of the enclosing class.

Upvotes: 3

Related Questions