About boost::asio::io
boost doc says that io_service may distribute work across threads in an arbitrary fashion, is it means that when i'm using TCP socket i may receive data into disorder? Because my reception handler may be distribute across threads in an arbitrary fashion.
When you schedule an async_read or a read using a boost io_service
, you act on a socket. Either through socket->read(...)
or read(socket ...)
. If you look through the documentation, there are some variants that accept a criteria for finishing the read, number of bytes, or matching condition. Using this you could have a connection which gives you say 20 bytes of data and you read it in 10 bytes to one thread and while that thread is processing the data, the next 20 bytes go to another thread. There are a few cases when you may want to do that, but usually you will want each thread to read in an entire packet.
If you want to ensure that only one thread is handling your io from a socket at a time, you can wrap the callbacks in a strand
. Here's a fairly generic example of what that would look like.
boost::asio::async_read(socket,
buffer(*responseBuffer),
transfer_all(),
strand.wrap(boost::bind(&YourClass::handleRead,
this, /*or use shared_from_this*/
placeholders::error)));
链接地址: http://www.djcxy.com/p/62672.html