英文:
Goroutine execution inside an http handler
问题
如果我在http处理程序中启动一个goroutine,即使返回响应,它是否会继续执行?以下是一个示例代码:
package main
import (
"fmt"
"net/http"
"time"
)
func worker() {
fmt.Println("worker started")
time.Sleep(time.Second * 10)
fmt.Println("worker completed")
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
go worker()
w.Write([]byte("Hello, World!"))
}
func main() {
http.HandleFunc("/home", HomeHandler)
http.ListenAndServe(":8081", nil)
}
在上面的示例中,无论何种情况,worker
goroutine是否会完成?或者是否存在不会完成的特殊情况?
英文:
If I start a goroutine inside an http handler, is it going to complete even after returning the response ? Here is an example code:
package main
import (
"fmt"
"net/http"
"time"
)
func worker() {
fmt.Println("worker started")
time.Sleep(time.Second * 10)
fmt.Println("worker completed")
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
go worker()
w.Write([]byte("Hello, World!"))
}
func main() {
http.HandleFunc("/home", HomeHandler)
http.ListenAndServe(":8081", nil)
}
In the above example, is that worker
goroutine going to complete in all situations ? Or is there any special case when it is not going to complete?
答案1
得分: 8
是的,它会完成,没有任何阻止它的东西。
唯一能够阻止goroutine完成的是从main()
函数返回(这也意味着程序执行结束,但在你的情况下永远不会发生)。还有其他导致不稳定状态的情况,比如内存耗尽。
英文:
Yes, it will complete, there's nothing stopping it.
The only thing that stops goroutines to finish "from the outside" is returning from the main()
function (which also means finishing the execution of your program, but this never happens in your case). And other circumstances which lead to unstable states like running out of memory.
答案2
得分: 5
是的,它将完全独立于您的请求进行完成。
这对于完成一些与您的响应无关的慢速操作非常有用,比如数据库更新(例如:更新视图计数器)。
英文:
Yes, it will complete totally independent of your request.
This can be useful to complete slow operations such as database updates that are not relevant to your response (e.g.: update a view counter).
答案3
得分: 0
TLDR:是的,在所有情况下都会完成。
http.ListenAndServe()
会启动自己的线程,并且会无限期地监听传入的请求(线程永远不会结束)。因此,主程序实际上永远不会结束,可以将其视为一个无限阻塞的调用(除非发生恐慌/崩溃)。而你编写的所有例程都将存在于由ListenAndServe()
启动的线程中,并且它们将始终完成。
希望这能对你的问题有更多的了解。
英文:
TLDR: YES it will complete in all situations<br>
http.ListenAndServe()
starts its own thread and it indefinitely listens to incoming requests (thread never ends). Hence, the main routine actually never ends, think of it like an endless blocking call,(unless there's any panic/crash). And all the routines that you would write would exist and finish within the thread started by ListenAndServe()
hence, it would always complete. <br>
Hope this gives you some more insight to your question.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论