【发布时间】:2019-04-05 12:19:25
【问题描述】:
创建多个 goroutines,这些 goroutines 在以多级方式处理时将具有嵌套的 goroutines(想象一棵 goroutines 树,每个级别可以有很多叶子)。
按顺序优雅地关闭这些 goroutine 并等待它们返回的惯用方式是什么?顺序是底部顶部(最深的孩子优先),并且还假设我不知道我将预先启动多少个 goroutine(动态)。
下面的示例只是以无序的方式优雅地关闭它们。
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
//level1
go func() {
fmt.Println("level1 started")
//level2
go func() {
fmt.Println("level2 started")
//level3
go func() {
fmt.Println("level3 started")
select {
case <-ctx.Done():
fmt.Println("Done called on level3")
case <-time.After(5* time.Second):
fmt.Println("After called on level3")
}
}()
select {
case <-ctx.Done():
fmt.Println("Done called on level2")
case <-time.After(7* time.Second):
fmt.Println("After called on level2")
}
}()
select {
case <-ctx.Done():
fmt.Println("Done called on level1")
case <-time.After(10* time.Second):
fmt.Println("After called on level1")
}
}()
time.Sleep(1*time.Second)
cancel()
time.Sleep(1 * time.Second)
}
【问题讨论】:
-
我强烈建议您评估您的设计,以找到一种方法来消除按顺序关闭的要求。您应该只需要同步并发数据访问,而且这种情况很少(当它们绝对必须共享内存时)。需要按顺序关闭 goroutine 意味着设计错误。
标签: go concurrency goroutine