提升异步套接字和boost :: thread

时间:2012-10-25 03:21:59

标签: c++ boost-asio boost-thread

我编写的TCP客户端应该能够同时发送和接收数据。 你能告诉我如何调用async_sendasync_receive是单独的线程吗?

换句话说如何调用

m_Socket.async_send(boost::asio::buffer(txBuf.c_str(), txBuf.length()+1),
    boost::bind(&TCPClient::sendingHandler, this, boost::asio::placeholders::error));

m_Socket.async_receive(boost::asio::buffer(rxBuf, maxBufLen),
    boost::bind(&TCPClient::sendingHandler, this, boost::asio::placeholders::error));

in

boost::thread receivingThread(boost::bind(...));
boost::thread sendingThread(boost::bind(...));

如果我再次在处理程序中调用async_sendasync_receive,它是否会正常工作?我需要一个不定式的循环来发送/接收数据。

1 个答案:

答案 0 :(得分:2)

主要思想是 - 在TCPClient::sendingHandler/receivingHandlerio_service's内的递归中发送和接收。这个io_service's在2个线程中调用 -

boost::thread receivingThread(boost::bind(...));
boost::thread sendingThread(boost::bind(...));

tutorial中可以清楚地看到这个想法。唯一的区别是你必须打电话并使用2个单独的io_service's

另一个选项是1 io_service并且多个线程调用io_service::run。但是你必须使用boost::asio::strand远程线程安全:

boost::asio::strand* _strand = new boost::asio::strand(io);
//then use it in handlers
boost::asio::async_read(*socket, 
                    boost::asio::buffer(msg.data(), result.size),
                    (*_strand).wrap(
                    boost::bind(&ConnectionInterface::parsePacket, shared_from_this(), boost::asio::placeholders::error)));