Web服务器请求会生成自己的goroutine吗? [英] Go web server requests spawn its own goroutine?
问题描述
我想知道goroutine和Go Web服务器在请求进入时到底如何工作:
I want to know how exactly goroutine and go web server works whenever requests come in:
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
在此代码中
-
每个对
/
的请求都调用handler
.这是否意味着每个请求都会生成自己的goroutine?还是产生自己的process
或thread
?是否有任何文档说明这些请求如何获得自己的goroutine?
Every request to
/
calls thehandler
. Does this mean each request spawns its own goroutine? Or does it spawns its ownprocess
orthread
? Is there any documentation on how those requests get its own goroutine?
其他语言如何处理此请求?例如,Python flask是否为每个请求启动自己的进程?
How do other languages handle this request? For example, does Python flask launch its own process for each request?
谢谢
推荐答案
Go's HTTP server (in net/http
) spawns a goroutine (not a thread) per request as per the docs for http://golang.org/pkg/net/http/#Server.Serve -
服务在侦听器l上接受传入连接,从而为每个连接创建一个新的服务goroutine.服务goroutine读取请求,然后调用srv.Handler对其进行回复.
Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.Handler to reply to them.
其他语言可以通过多种方式处理此问题,包括:
Other languages handle this in many ways, including:
- 基于事件的体系结构ala node.js 1 和
- 多个进程和/或线程(或两者兼有),其中管理器"根据正在阻止的(和不阻止的)在活动线程之间切换
我建议阅读 https://www.digitalocean.com/community/tutorials/a-comparison-of-web-servers-for-python-based-web-applications (适用于Python),一些见识.
I'd suggest reading https://www.digitalocean.com/community/tutorials/a-comparison-of-rack-web-servers-for-ruby-web-applications for an example of how some of the Ruby web servers do things (which include the approaches above), and https://www.digitalocean.com/community/tutorials/a-comparison-of-web-servers-for-python-based-web-applications for Python, which should give some insight.
这篇关于Web服务器请求会生成自己的goroutine吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!