I'm trying to spin a dedicated thread pinned to a CPU-core to read some data from a web-socket.
All the resources on that core are mainly dedicated to read data from the socket and parse it.
I do not want a high-throughput, I want a minimum latency to read/decode/dispatch the message, reducing the jitter to the minimum.
I'm using boost::beast
/boost::asio
to read the data from the socket in a synchronous-blocking way, so I've disabled thread-support in BOOST_ASIO_DISABLE_THREADS
.
The code looks like this:
while (state_.load(std::memory_order_acquire) == state::running) {
ws_client_.read(buffer_);
if (ws_client_.is_message_done()) {
// ...
}
}
This code works fine, but It does not satisfies my needs. I can see that the CPU usage has dropped and that most of the time the thread is sleeping.
I've read that the right way to spin a boost::asio
service is by calling poll
or poll_one
in the boost::asio::io_context
, so I've tried this:
while (state_.load(std::memory_order_acquire) == state::running) {
ioc.poll();
}
This keeps the CPU usage at 100%, exactly what I want. So I'm doing this:
void connect(...) {
// connected =)
ws.async_read(buffer, std::ref(*this));
}
void operator()(const boost::system::error_code& ec, std::size_t bytes_written) {
// ...
// I'm done parsing, query next
ws.async_read(buffer, std::ref(*this));
}
void poll() {
ioc.poll();
}
This seems to solve my issues, I wonder if there is a more efficient/elegant way to do this without the need to bind a function callback?