golang 每日一练 WaitGroup和context 监控方式

控制并发有两种经典的方式,一种是WaitGroup,另外一种就是Context。


WaitGroup 方式:

var wg sync.WaitGroup

func fun1(i chan int) {
time.Sleep(2 * time.Second)
fmt.Println(<-i)
wg.Done()
}

func main() {
wg.Add(2)
ch1 := make(chan int)
ch2 := make(chan int)

go fun1(ch1)
go fun1(ch2)

ch1 <- 1
      ch2 <- 2

      wg.Wait()
fmt.Println("全部 goroutine 运行结束")
}


Context 方式:

func main()  {
ctx,cancel := context.WithCancel(context.Background())
go watch(ctx,"监控一")
go watch(ctx,"监控二")
go watch(ctx,"监控三")

time.Sleep(6 * time.Second)
fmt.Println("结束监控")
cancel()

time.Sleep(2*time.Second)

}

func watch(ctx context.Context,name string) {
for {
select {
case <- ctx.Done():
fmt.Println(name+"监控结束,退出")
return
             default:
fmt.Println(name+"监控中")
time.Sleep(2*time.Second)
}
}
}



在线交流