监听多个套接字:选择与多线程 [英] Listening to multiple sockets: select vs. multi-threading

查看:74
本文介绍了监听多个套接字:选择与多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务器需要侦听来自多个套接字(10-20)的传入数据.进行一些初始化之后,这些套接字将被创建并且不会更改(即,不接受任何新的套接字,并且在服务器的整个生命周期中都不会关闭它们).

A server needs to listen to incoming data from several sockets (10-20). After some initializations, those sockets are created and do not change (i.e. no new sockets accepted, and none of them is expected to close during the lifetime of the server).

一种选择是在所有套接字上为select(),然后处理每个套接字的传入数据(即路由到适当的处理功能).

One option is to select() on all sockets, then deal with incoming data per socket (i.e. route to proper handling function).

另一种选择是每个套接字打开一个线程,让每个线程recv()并处理输入.

Another option is to open one thread per socket and let each thread recv() and handle the input.

(第一个选项的好处是设置了超时时间,但是在这种情况下这不是问题, 因为所有套接字都非常活跃).

(The first option has the benefit of setting a timeout, but this is not an issue in this case, since all the sockets are quite active).

假设以下内容:Windows服务器,具有足够的内存,使得20 MB(对于20个线程)不会出现问题,那么这些选项中的任何一个是否有望比另一个更快?

Assuming the following: Windows server, has enough memory such that 20MB (for the 20 threads) is a non-issue, is any of those options expected to be faster then the other?

推荐答案

您的应用程序中没有太多内容.通常,使用每套接字线程比异步方法更容易,因为它是一个更简单的总体结构,并且更容易维护状态.

There's not much in it in you app. Typically, using a thread-per-socket is easier than asynchronous approaches because it's a simpler overall structure and it's easier to maintain state.

这篇关于监听多个套接字:选择与多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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