缓存channel使用for-range?

bvaccc · · 1597 次点击
``` Go package main import ( "fmt" "runtime" "sync" ) var wg sync.WaitGroup func main() { runtime.GOMAXPROCS(runtime.NumCPU()) c := make(chan bool, 10) for i := 0; i < 10; i++ { wg.Add(1) go Go(c, i) } wg.Wait() close(c) for i := range c { //如何使用`for-range`循环实现? // use i fmt.Println(i) } } func Go(c chan bool, index int) { defer wg.Done() a := 0 for i := 0; i < 10000000; i++ { a += i } fmt.Println(index, a) c <- true } ```
#7
更多评论
stevewang
耶和华是我的牧者,我必不至缺乏。
这里不适合用range,因为需要配合close,但是找不到合适的地方去close channel
#1
package main import ( "fmt" "runtime" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) cs := make([]chan bool, 10) for i := 0; i < 10; i++ { cs[i] = make(chan bool, 1) go Go(cs[i], i) } for _, c := range cs { <-c } } func Go(c chan bool, index int) { a := 0 for i := 0; i < 10000000; i++ { a += i } fmt.Println(index, a) c <- true } 改成slice试试?
#2