gpt4 book ai didi

Goroutine 从 main 返回后没有执行完。为什么?

转载 作者:数据小太阳 更新时间:2023-10-29 03:45:47 26 4
gpt4 key购买 nike

我正在尝试理解 golang 中的上下文。我从 https://golang.org/pkg/context/#example_WithCancel 复制了一个例子并稍微改变一下: Playground :https://play.golang.org/p/Aczc2CqcVZR

package main

import (
"context"
"fmt"
"time"
)

func main() {
// gen generates integers in a separate goroutine and
// sends them to the returned channel.
// The callers of gen need to cancel the context once
// they are done consuming generated integers not to leak
// the internal goroutine started by gen.
gen := func(ctx context.Context) <-chan int {
dst := make(chan int)
n := 1
go func() {
for {
select {
case <-ctx.Done():
fmt.Println("DONE")
return // returning not to leak the goroutine
case dst <- n:
n++
}
}
fmt.Println("END")
}()
return dst
}

ctx, cancel := context.WithCancel(context.Background())

defer time.Sleep(1 * time.Second)
defer fmt.Println("Before cancel")
defer cancel() // cancel when we are finished consuming integers
defer fmt.Println("After cancel")

channel := gen(ctx)
for n := range channel {
fmt.Println(n)
if n == 5 {

break
}
}

fmt.Println( <-channel)

}

注释掉

defer time.Sleep(1 * time.Second)

“完成”永远不会被打印出来。 Playground :(https://play.golang.org/p/K0OcyZaj_xK)

我希望在匿名函数中启动的 go 例程仍然处于事件状态。一旦 cancel() 由于被延迟而被调用,select 不应再像

那样阻塞
case <-ctx.Done():

应该可用。然而它似乎刚刚结束,除非我等待 1 秒并给它时间。这种行为似乎是非常错误的。

最佳答案

This behavior seems very wrong.

不是。这就是指定程序执行的方式。在 main 及其延迟函数返回后,程序退出。

Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.

https://golang.org/ref/spec#Program_execution

关于Goroutine 从 main 返回后没有执行完。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55952250/

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