Golang goroutine 退出结束分析

217 阅读1分钟

问题

  1. Main 方法退出后(Main方法执行完毕,或者os.Exit), 所有子 goroutine都会马上退出吗?

  2. Main 方法持续运行, 但是子 Goroutine 退出会导致它所有孙 Goroutine 立即退出吗?

验证

1. Main方法退出后(Main方法执行完毕,或者os.Exit), 所有子 goroutine都会马上退出吗?

回答: 是的

验证代码如下:


import (

"fmt"

"time"

)


func main() {

fmt.Println("Hello, 世界")

go A()

go B()

}


func A() {

fmt.Println("======aaaaaaaa=======")

go B()

}


func B() {

time.Sleep(5 * time.Second)

fmt.Println("======bbbbb=======")

}

执行结果如下


Hello, 世界


Program exited.

2. Main 方法持续运行, 但是子 Goroutine 退出会导致它所有孙 Goroutine 立即退出吗?

回答:不会, 只要 Main 方法没有退出, 所有的 Goroutine 都会正常执行直到结束

验证代码如下:


package main


import (

"fmt"

"time"

)


func main() {

fmt.Println("Hello, 世界")

go A()

time.Sleep(10 * time.Second)

}


func A() {

fmt.Println("======aaaaaaaa=======")

go B()

}


func B() {

time.Sleep(5 * time.Second)

fmt.Println("======bbbbb=======")

}

执行结果如下


Hello, 世界

======aaaaaaaa=======

======bbbbb=======


Program exited.