作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
<分区>
我知道如果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)
}
输出
[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.
问题:
我是一名优秀的程序员,十分优秀!