我的问题是关于线程的使用。我正在制作一个通过TCP/IP连接到设备的应用程序。我使用的是boost::asio lib。我决定分别使用读或监听线程和写线程来监听和写入设备。我的困惑是,创建处理通信的套接字的函数也应该是一个线程。谢谢:)
发布于 2013-03-01 05:23:53
在我的客户机类中,我创建了两个工作线程来处理消息的发送和接收,这些消息用于到多个服务器的多个连接。创建这两个工作线程的线程恰好是用户界面线程。下面是我的代码:
// Create the resolver and query objects to resolve the host name in serverPath to an ip address.
boost::asio::ip::tcp::resolver resolver(*IOService);
boost::asio::ip::tcp::resolver::query query(serverPath, port);
boost::asio::ip::tcp::resolver::iterator EndpointIterator = resolver.resolve(query);
// Set up an SSL context.
boost::asio::ssl::context ctx(*IOService, boost::asio::ssl::context::tlsv1_client);
// Specify to not verify the server certificiate right now.
ctx.set_verify_mode(boost::asio::ssl::context::verify_none);
// Init the socket object used to initially communicate with the server.
pSocket = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(*IOService, ctx);
//
// The thread we are on now, is most likely the user interface thread. Create a thread to handle all incoming socket work messages.
if (!RcvThreadCreated)
{
WorkerThreads.create_thread(boost::bind(&SSLSocket::RcvWorkerThread, this));
RcvThreadCreated = true;
WorkerThreads.create_thread(boost::bind(&SSLSocket::SendWorkerThread, this));
}
// Try to connect to the server. Note - add timeout logic at some point.
boost::asio::async_connect(pSocket->lowest_layer(), EndpointIterator,
boost::bind(&SSLSocket::HandleConnect, this, boost::asio::placeholders::error));工作线程处理所有套接字I/O。这取决于您正在做什么,但是服务套接字的两个工作线程需要从另一个线程创建。如果你愿意,另一个线程可以是用户界面线程或主线程,因为它会很快返回。如果您有多个到服务器或客户端的连接,则由您决定是否需要多个线程集来为它们提供服务。
发布于 2013-03-01 05:04:48
这取决于你是否想同时读写。在这种情况下,您将需要一个用于读取的线程和一个用于写入的线程,但是您必须正确地同步这两个线程,以防传入和传出设备的流彼此之间存在某种关系(它们可能会这样做)。然而,对我来说,与设备交谈听起来就像是一个任务,你需要建立一个连接,发送一些请求,等待并阅读答案,发送另一个请求,等待并阅读下一个答案,等等。在这种情况下,只使用一个线程就足够了,让你的生活变得容易得多。
https://stackoverflow.com/questions/15145418
复制相似问题