前言
父gorutine如何优雅得控制子gorutine退出?
前戏
通过全局变量
package main import ( "fmt" "sync" "time" ) var wg sync.WaitGroup var signal bool func child() { defer wg.Done() for { //通过程序逻辑来控制gorutine退出 if signal { break } time.Sleep(time.Second * 2) fmt.Println("我是child gorutine") } } func main() { wg.Add(1) go child() time.Sleep(time.Second * 10) signal = true wg.Wait() }