i am writing a chat server with file transfer to learn asio, workers io_context.run on multiple threads, and async_accept/async_read/async_write io_context.run on 1 thread, and all msgs are added to worker with worker.add() below. it will be handling heavy activity from the users (files and msgs).
is this the correct way of handling users? 1 thread to read/write from all users, and multiple threads to handle the data? or should it be the reverse? or 50/50? and is this the correct way to implement a worker with asio::strand?
worker::worker(asio::io_context& context):
io_context_(context), // for workers only
strand_(context)
{
}
void worker::add(const std::vector<char> &msg) {
asio::post(strand_, [this, msg]() {
bool handling = !messages_.empty();
messages_.push_back(msg);
if (!handling) {
handle_message();
}
});
}
void worker::handle_message() {
asio::post(io_context_, asio::bind_executor(strand_, ([this]() {
auto msg = messages_.front();
// do something with msg, maybe disk io,
// or asio::post() to another strand
messages_.pop_front();
if (!messages_.empty())
handle_message();
})));
}
Aucun commentaire:
Enregistrer un commentaire