I'm curious if using the asynchronous read function in Boost ASIO would have any performance benefits compared to using a separate thread that does reads synchronously. The use case would be having to always listen for data from a remote host.
In the async case, I believe ioservice.run() will block the thread until there is data to be read. In the synchronous case, the boost::asio:read call will block until there is data to be read. Is there any advantage to using async reads? It seems like if the application needs to anything in the background while waiting for data, a separate thread will be also be needed when using async_read since ioservice_run() will block.
The code would be something like the following (may not compile, just trying to get the idea across):
Using async reads:
#include <iostream>
#include <boost/asio.hpp>
void read_handler(const boost::system::error_code &ec)
{
//Read incoming message
//Chain the callbacks
socket.async_read(read_handler);
}
int main()
{
std::string host = "192.168.1.3";
std::string port = "8888";
std::cout << "Attemping connection to host " << host << " on port " << port << std::endl;
boost::asio::connect(tcpSocket, resolver.resolve({host, port}));
std::cout << "Connected" << std::endl;
socket.async_read(read_handler);
//Will block until there is data to read?
ioservice.run();
return 0;
}
Using synchronous reads in a separate thread:
#include <thread>
void readThread()
{
while(true)
{
//Will block until there is data to read
boost::asio::read(tcpSocket, boost::asio::buffer(buffer, size));
}
}
int main()
{
std::string host = "192.168.1.3";
std::string port = "8888";
std::cout << "Attemping connection to host " << host << " on port " << port << std::endl;
boost::asio::connect(tcpSocket, resolver.resolve({host, port}));
std::cout << "Connected" << std::endl;
std::thread r{readThread};
return 0;
}
Thanks! Please forgive my inexperience with asio and networking :)