Go - WaitGroup
package main
import (
"fmt"
"sync"
)
//WaitGroup用于等待一组线程的结束。父线程调用Add方法来设定应等待的线程的数量。每个被等待的线程在结束时应调用Done方法。同时,主线程里可以调用Wait方法阻塞至所有线程结束
func main() {
var wg sync.WaitGroup
wg.Add(2)
c := make(chan int)
go send(c, &wg)
go receive(c, &wg)
wg.Wait()
}
func receive(c chan int, wg *sync.WaitGroup) {
for i := range c {
fmt.Println(i)
}
wg.Done()
}
func send(c chan int, wg *sync.WaitGroup) {
for i := 0; i < 10; i++ {
c <- i
}
close(c)
wg.Done()
}