Creating multiple goroutines which will have nested goroutines while processing in a multilevel manner (Imagine a tree of goroutines each level can have many leaves).
What is the idiomatic way to gracefully shutdown these goroutines in order and wait for them to come back? Order is the bottom top (deepest child first) and also assume I dont know how many goroutines I will launch beforehand (dynamic).
the example below just gracefully shuts them down in an non ordered manner.
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)
}