I've been coding this server for quite some time now. I am calling io_service::run from more than 1 thread, but I am not sure if I ned to use strand here. Since I am never calling async_read more than once. Though it is possible that I call async_write more than once if other connections need to send something to others. This is the code I have so far
void Session::RecvPacket()
{
boost::asio::async_read(m_socket, boost::asio::buffer(m_recv_buffer, len),
boost::bind(&Session::OnRead, this, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void Session::OnRead(const boost::system::error_code &e, size_t packet_length, size_t bytes_transferred)
{
if (e || bytes_transferred != packet_length)
{
if (e == boost::asio::error::operation_aborted)
return;
Stop();
return;
}
// do something and most likely send a packet back
RecvPacket();
}
void Session::SendPacket(packet &p)
{
boost::mutex::scoped_lock lock(send_mut);
dword len = p.Lenght();
m_crypt->makeheader(p.GetRaw().get(), static_cast<word>(len - 4));
m_crypt->encrypt(p.GetRaw().get() + 4, len - 4);
boost::asio::async_write(m_socket, boost::asio::buffer(p.GetRaw().get(), len),
boost::bind(&Session::OnPacketSend, this, len, boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred, p.GetRaw()));
}
I am not sure wheter this is threadsafe or not. If only the send part is not threadsafe since I can send more than 1 packet at once (which is going to happen) should I only use a strand there?
Gz