我知道,如果goroutine B是从某个goroutine A开始的,如果goroutine A结束,那么无论goroutine B走多远,它都会被强制结束。
\nfunc main() {\n go simulateGinAPI()\n fmt.Println("finish...")\n}\n\nfunc simulateGinAPI() {\n fmt.Println("ginAPI....")\n go backgroundProcess()\n}\n\n\nfunc backgroundProcess() {\n fmt.Println("calculating...")\n fmt.Println(calculate(45))\n}\n\nfunc calculate(x int) int {\n if x < 2 {\n return x\n }\n return calculate(x-1) + calculate(x-2)\n}\nRun Code Online (Sandbox Code Playgroud)\n输出
\nfunc main() {\n go simulateGinAPI()\n fmt.Println("finish...")\n}\n\nfunc simulateGinAPI() {\n fmt.Println("ginAPI....")\n go backgroundProcess()\n}\n\n\nfunc backgroundProcess() {\n fmt.Println("calculating...")\n fmt.Println(calculate(45))\n}\n\nfunc calculate(x int) int {\n if x < 2 {\n return x\n }\n return calculate(x-1) + calculate(x-2)\n}\nRun Code Online (Sandbox Code Playgroud)\n正如输出日志所示。斐波那契和的结果不会被注销,而是仅注销“完成”。
\n然而,正如下面的代码所示,如果我们从 Gin 的句柄开始 goroutine,即使发送了响应,计算斐波那契和结果的 goroutine 仍然会运行到最后。
\nfinish...\nRun Code Online (Sandbox Code Playgroud)\n\n输出
\n[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default\n[GIN-debug] Listening and serving HTTP on :8080\ncalculating...\n[GIN] 2021/12/20 - 11:31:46 | 200 | 56.425\xc2\xb5s | ::1 | GET "/ping"\n1134903170 <- result of Fibonacci\'s sum.\n\nRun Code Online (Sandbox Code Playgroud)\n问题:
\n我知道,如果goroutine B是从某个goroutine A开始的,如果goroutine A结束,那么无论goroutine B走多远,它都会被强制结束。
这是不正确的。如果main函数退出,所有的 goroutine 也会退出。
但是如果main函数继续运行,尽管 goroutine 调用函数退出,该 goroutine 仍将继续运行。
这也发生在你的例子中。
您的示例代码在计算总和之前就退出了Fibonacci。但您的服务器代码继续运行。这就是代码中出现这种行为的原因。
如果您稍微更改一下示例代码,您会发现您的程序还计算斐波那契和。
这是示例: https: //goplay.tools/snippet/dMCyUqweyu8
| 归档时间: |
|
| 查看次数: |
1706 次 |
| 最近记录: |