单线程中的多连接 [英] Mutliple connections in a Single Thread

查看:108
本文介绍了单线程中的多连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在单个线程中处理多个TCP连接?

目前,我正在为每个TCP连接创建单独的线程.用于特定连接的数据读取和写入在相应的线程中完成.此应用程序旨在在嵌入式板[ARM9]上运行.

但是我们要使同一应用程序在另一块板上运行,该板上具有客户特定的操作系统,该操作系统仅管理单线程.通过使用选择",我们能够做到这一点,但是我们却缺少了一些要求.有什么方法可以并行处理这些请求.

解决方案

是否可以在单个线程中处理多个TCP连接? blockquote>

绝对...将套接字切换为非阻塞模式,并在单个线程中管理许多连接.

hSocket = socket(PF_INET, SOCK_STREAM, 0);
fcntl(hSocket, F_SETFL, O_NONBLOCK);


然后使用一个函数来等待,直到您的套接字之一更改状态为止,例如select().自从您提到ARM9以来,您需要查看SDK的文档.如果它支持普通的套接字功能(伯克利风格的网络),则您的嵌入式操作系统很有可能也将支持它.

有关如何在Linux/Windows平台上完成此操作的更多详细信息和示例源代码,请参见:
Beej的网络编程指南(同步I/O复用)和 Winsock程序员的常见问题解答(基于选择的服务器).

希望这会有所帮助!


我建​​议您考虑使用线程池.让主线程接受连接,但由线程池完成工作.


请忽略:这是一个重新发布,我已将其清除.


Is it possible to handle Multiple TCP Connections in a single thread?

Currently I am creating seperate threads for each TCP Connection. Data reading and writing for a particular connection is done in the respective threads. This application is meant to run on an embedded board[ARM9].

But we want to make the same application run on another board, that has a customer specific operating system which manages only single thread. By using the ''select'' we were able to do it, but we are missing some of the request. Is there any way to handle these requests parallely.

解决方案

Is it possible to handle Multiple TCP Connections in a single thread?



Absolutely... switch sockets into non-blocking mode and manage many connections within a single thread.

hSocket = socket(PF_INET, SOCK_STREAM, 0);
fcntl(hSocket, F_SETFL, O_NONBLOCK);


Then use a function to wait until one of your sockets changes status, something like select(). Since you mentioned ARM9 you need to check your SDK''s documentation. If it supports normal socket functions (Berkeley style networking) there is a fair chance your embedded OS will support it too.

For more details and example source code how this could be done on a Linux/Windows platform see:
Beej''s guide to networking programming (synchronous I/O multiplexing) and Winsock Programmer''s FAQ (select-based server).

Hope this helps!


I''ll recommend that you consider using a threadpool. Let the main thread accept connections, but the threadpool do the work.


Please ignore: This is a repost and I''ve wiped it off.


这篇关于单线程中的多连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆