go for循环中调用goroutine ,使用chan进行通信
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)) }
stay hungry stay foolish!