“每个连接一个线程”的优点是什么?在 HTTP 服务器中?
如果我正在编写 HTTP 服务器,为什么我应该考虑在自己的线程中处理每个 HTTP 连接?
我读过很多论据,认为事件驱动的 HTTP 服务器比线程驱动的服务器更快、更具可扩展性。 (例如,请参阅 Ars Technica 上的 Nginx)。然而,世界上最流行的服务器 Apache 是线程驱动的。为什么?有什么优点?
If I was programming an HTTP server, why should I consider handling every HTTP connection in its own thread?
I've read plenty of arguments that event-driven HTTP servers are faster and more scalable than thread-driven ones. (For example, see Ars Technica on Nginx). And yet Apache, the world's most popular server, is thread-driven. Why? What are the advantages?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编写代码很简单。
基本上,如果没有语言支持(例如 C# 和 VB 将在其下一个版本中获得)和真正好的库,编写异步代码是很困难的。并非不可能,毫无疑问,那些能够做到这一点的人肯定会发表评论,但这比同步版本更难。我们更擅长考虑只从上到下执行的代码,而不是必须可重入的代码等。
根据您的平台,现在线程可能相当便宜 - 因此,通过适当的池化,对于不需要一次处理那么多请求的服务器来说,每个请求线程模型非常有效。当然,这对于长轮询或主要需要将请求委托给其他服务的服务器来说很糟糕,这些服务可能需要“一段时间”才能返回(即使只有十分之一秒)。后一类服务器应该能够处理巨大的请求率,因为它们只进行最少的处理来完成其工作 - 但如果它们为每个请求占用一个线程,那么在等待另一个服务时就会阻塞返回,这可能会非常浪费,尤其是内存。
It's simple to code against.
Basically, without language support (such as C# and VB will be getting in their next versions) and really good libraries, writing asynchronous code is hard. Not impossible, and no doubt there will be comments from those who are able to do it standing on their heads, but it's harder than the synchronous version. We're much better at thinking about code which just executes top to bottom than code which has to be reentrant etc.
Depending on your platform, threads can be quite cheap these days - so with appropriate pooling, the thread-per-request model works pretty well for servers who don't need to handle that many requests at a time. It sucks for long-polling, of course, or servers which mostly need to delegate requests to other services which may take "a while" to come back (even if that's only a tenth of a second). The latter class of server should be able to handle huge request rates as they're only doing minimal processing to do their work - but if they hog a thread for each request simply to block while waiting for another service to come back, that can be very wasteful, particularly of memory.