参考
golang 控制并发有两种经典方式:WaitGroup 和 Context - 孤独信徒 - 博客园
Golang控制并发有两种经典的方式,一种是WaitGroup,另外一种就是Context。
cancel是主动停止协程(不管是否执行完毕),而WaitGroup是协程执行完毕后自己主动结束的
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)
}
}
}
本文探讨了Golang中控制并发的两种经典方法:WaitGroup,通过示例展示其工作原理,以及Context,包括如何使用`WithCancel`来优雅地管理任务取消。
775

被折叠的 条评论
为什么被折叠?



