go使用协程并发并等待全部协程结束的方法
第一种,基于原生带缓存的channel
package main import "fmt" func main() { done := make(chan int, 10) for i := 0; i < cap(done); i++ { go func(j int) { fmt.Println("你好,世界" + fmt.Sprintf("%v", j)) done <- 1 }(i) } //等待N个后台线程完成 for i := 0; i < cap(done); i++ { <-done } }
第二种,通过使用使用sync.WaitGroup来等待
package main import ( "sync" "fmt" ) func main() { var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(j int) { fmt.Println("你好,世界" + fmt.Sprintf("%v", j)) wg.Done() }(i) } wg.Wait() }
- 上一篇 »Python协程原理全面分析
- 下一篇 »Python 异步如何使用等待有时间限制协程?