<p>为每个连接生成一个新线程是一个非常糟糕的设计选择。
如果你被很多人打了怎么办?</p>
<p>事实上,使用线程等待网络IO是不值得的。您的程序变得非常复杂,而且您完全没有好处,因为在线程中等待网络不会让您更快地等待。在这种情况下,使用线程只会失败。</p>
<p>以下文本来自python文档:</p>
<blockquote>
<p>There are only two ways to have a
program on a single processor do “more
than one thing at a time.”
Multi-threaded programming is the
simplest and most popular way to do
it, but there is another very
different technique, that lets you
have nearly all the advantages of
multi-threading, without actually
using multiple threads. It’s really
only practical if your program is
largely I/O bound. If your program is
processor bound, then pre-emptive
scheduled threads are probably what
you really need. Network servers are
rarely processor bound, however.</p>
</blockquote>
<p>如果是处理器绑定的服务器案例。您总是可以留下另一个进程/线程来完成处理器部分。继续:</p>
<blockquote>
<p>If your operating system supports the
select system call in its I/O library
(and nearly all do), then you can use
it to juggle multiple communication
channels at once; doing other work
while your I/O is taking place in the
“background.” Although this strategy
can seem strange and complex,
especially at first, it is in many
ways easier to understand and control
than multi-threaded programming.</p>
</blockquote>
<p>因此,不要使用线程,而是使用非阻塞输入/输出:收集列表中的套接字,并使用带有<a href="http://docs.python.org/library/select.html#select.select" rel="noreferrer">select.select</a>的事件循环来知道哪个套接字有数据要读取。用一根线做。</p>
<p>您可以选择像<a href="http://twistedmatrix.com/" rel="noreferrer">twisted</a>这样的python异步网络框架来实现这一点。这会让你省去很多头疼的事。Twisted的代码已经改进了很多年,并且涵盖了一些你需要花时间掌握的角落案例。</p>
<p><strong>编辑</strong>:任何现有的异步IO库(如Twisted)都是python代码。你本可以自己写的,但已经为你写了。我不明白为什么你不使用这些库中的一个来编写自己最差的代码,因为你是一个初学者。网络IO很难实现。</p>