package main import ( "fmt" "runtime" "strconv" "sync" ) func main() { var wg sync.WaitGroup ch1 := make(chan int, 100) runtime.GOMAXPROCS(runtime.NumCPU()) wg.Add(100) for i := 0; i < 100; i++ { go func(index int) { ch1 <- index wg.Done() }(i) } //不关闭会报 all goroutines are asleep go func() { wg.Wait() close(ch1) }() //defer close(ch1) index := 0 for i := range ch1 { fmt.Println(i) index++ } fmt.Println("index:" + strconv.Itoa(index)) }