goroutine 并发常见问题实践

2020-03-18  本文已影响0人  pubalabala

程序退出时运行的 goroutine 会不会被终止

测试代码:

import (
    "time"
    "fmt"
)

func main() {
    for i := 0; i < 10; i ++ {
        go func(j int) {
            fmt.Println(j)
        }(i)
    }
    time.Sleep(3*time.Microsecond)
    return
}

运行结果:

➜  test go run ./test_goroutine.go
0
1
2
3
4
5
6
7
8
9
➜  test go run ./test_goroutine.go
5
4
6
➜  test go run ./test_goroutine.go
➜  test go run ./test_goroutine.go

结论:主程序结束时还在运行中的 goroutine 也会终止。

怎样让主程序等待所有 goroutine 退出:

上一篇 下一篇

猜你喜欢

热点阅读