Go web服务器请求会生成自己的goroutine吗?

huangapple go评论99阅读模式
英文:

Go web server requests spawn its own goroutine?

问题

我想知道每当请求到来时,goroutine和Go Web服务器是如何工作的:

在这段代码中,

  1. 每个对/的请求都会调用handler函数。这是不是意味着每个请求都会生成自己的goroutine?还是生成自己的进程线程?有没有关于这些请求如何获得自己的goroutine的文档?

  2. 其他编程语言是如何处理这个请求的?例如,Python的Flask框架是为每个请求启动自己的进程吗?

谢谢。

英文:

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)
}

In this code,

  1. Every request to / calls the handler. Does this mean each request spawns its own goroutine? Or does it spawns its own process or thread? Is there any documentation on how those requests get its own goroutine?

  2. How do other languages handle this request? For example, does Python flask launch its own process for each request?

Thanks,

答案1

得分: 7

Go的HTTP服务器(在net/http中)根据http://golang.org/pkg/net/http/#Server.Serve文档,为每个请求生成一个goroutine(而不是线程)。

> Serve在监听器l上接受传入的连接,为每个连接创建一个新的服务goroutine。服务goroutine读取请求,然后调用srv.Handler来回复它们。

其他语言以多种方式处理这个问题,包括:

  • 基于事件的架构,比如node.js1
  • 多进程和/或多线程(或两者兼有),其中“管理器”根据阻塞情况(以及非阻塞情况)切换活动线程

我建议阅读https://www.digitalocean.com/community/tutorials/a-comparison-of-rack-web-servers-for-ruby-web-applications,了解一些Ruby Web服务器的工作方式(包括上述方法),以及https://www.digitalocean.com/community/tutorials/a-comparison-of-web-servers-for-python-based-web-applications,了解Python的一些见解。

英文:

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 -

> 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:

  • Event-based architectures ala node.js1 and
  • Multiple processes and/or threads (or both) where the "manager" switches between the active thread based on what is blocking (and what isn't)

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.

huangapple
  • 本文由 发表于 2015年6月29日 13:30:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/31108408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定