gpt4 book ai didi

go - 为什么从 Gin 的处理程序开始例行工作直到结束

转载 作者:行者123 更新时间:2023-12-01 23:08:12 25 4
gpt4 key购买 nike

<分区>

我知道如果goroutine B是从某个goroutine A开始的,如果goroutine A结束了,不管goroutine B走多远,都会被强行结束。

func main()  {
go simulateGinAPI()
fmt.Println("finish...")
}

func simulateGinAPI() {
fmt.Println("ginAPI....")
go backgroundProcess()
}


func backgroundProcess() {
fmt.Println("calculating...")
fmt.Println(calculate(45))
}

func calculate(x int) int {
if x < 2 {
return x
}
return calculate(x-1) + calculate(x-2)
}

输出

finish...

如输出日志所示。 Fibonacci 和的结果不会被注销,而只会被“finish”注销。


但是,如下面的代码所示,如​​果我们从一个Gin的句柄开始gorouting,即使响应已经发送,计算斐波那契和结果的goroutine仍然会运行到最后。


func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
go backgroundProcess()
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

func simulateGinAPI() {
fmt.Println("ginAPI....")
go backgroundProcess()
}


func backgroundProcess() {
fmt.Println("calculating...")
fmt.Println(calculate(45))
}

func calculate(x int) int {
if x < 2 {
return x
}
return calculate(x-1) + calculate(x-2)
}

enter image description here

输出

[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
calculating...
[GIN] 2021/12/20 - 11:31:46 | 200 | 56.425µs | ::1 | GET "/ping"
1134903170 <- result of Fibonacci's sum.

问题:

  1. 为什么从 gin 句柄开始的 goroutine 没有结束在 Gin 的句柄发送响应后强制执行?
  2. handle 的 goroutine 是否应该在 handle 之后结束回复已发送?
  3. 从handle开始的goroutine不应该被强行结束吗句柄上的 goroutine 结束?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com