1

我的问题是关于线程的使用。我正在制作一个通过 TCP/IP 连接到设备的应用程序。我正在使用 boost::asio lib。我决定使用读取或侦听线程和写入线程分别用于侦听和写入设备。我的困惑是创建处理通信的套接字的函数也应该是一个线程。谢谢 :)

4

2 回答 2

2

在我的客户端类中,我创建了 2 个工作线程来处理发送和接收消息,这些消息用于与多个服务器的多个连接。创建这两个工作线程的线程恰好是用户界面线程。这就是我的代码的样子:

// 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。这取决于您在做什么,但是需要从另一个线程创建用于服务套接字的 2 个工作线程。如果您愿意,另一个线程可以是用户界面线程或主线程,因为它会很快返回。如果您与服务器或客户端有多个连接,则由您决定是否需要一组以上的线程来为它们提供服务。

于 2013-02-28T21:23:52.690 回答
0

这取决于您是否要同时读取和写入。在这种情况下,您需要一个线程用于读取和一个线程用于写入,但您必须正确同步这些线程,以防进出设备的两个流相互关联(它们可能会做什么)。但是,在我看来,与设备交谈就像是建立连接、发送一些请求、等待并阅读答案、发送另一个请求、等待并阅读下一个答案等的任务。在这种情况下,只使用一个线程就足够了,让你的生活更轻松。

于 2013-02-28T21:04:48.220 回答