问题
I'm trying to understand the internal work of boost::asio
library, which is really great. I've written a simple client that sends one message to a server.
The question is - in which thread does it really send the message?
Since I use async_write()
method, it returns immediately after calling and doesn't send anything. I've commented the io_service.run()
method, and after that the handler was not called (that's okay), but the message was sent! (I've checked it in server logs)
By the way, I don't use -lpthread
, just -lboost_system
while compiling, so I assume the whole program works in one thread and there are no "hidden" threads.
I cannot make head or tail of where was the message sent.
#include <iostream>
#include <boost/asio.hpp>
const std::string str("HELLO!");
int main()
{
boost::asio::io_service io_service;
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 33333);
boost::asio::ip::tcp::socket socket(io_service);
boost::system::error_code ec;
boost::asio::connect(socket, &endpoint, ec);
boost::asio::async_write(socket, boost::asio::buffer(str),
[](const boost::system::error_code& ec, std::size_t length)
{
if (!ec)
{
std::cout << "Sent!" << std::endl;
}
else
{
std::cout << "Err: " << ec.message() << std::endl;
}
});
//io_service.run();
return 0;
}
回答1:
The message would have been sent (or at least queued in the network stack, perhaps to be handled by a kernel thread, or some other implementation-dependent mechanism that you shouldn't need to care about) during the call to async_write
. There's no need to defer that, if it can be done without blocking the calling thread, which it typically can be.
The completion handler won't be called until the io_service
is run, and is notified that the message has been sent.
来源:https://stackoverflow.com/questions/24776235/boostasio-in-which-thread-is-the-message-sent