代码如下:
```go
package main
import (
"fmt"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
c := make(chan bool, 10)
for i := 0; i < 10; i++ {
go Go(c, i)
}
for i := 0; i < 10; i++ { //如何使用`for-range`循环实现?
<-c
}
}
func Go(c chan bool, index int) {
a := 0
for i := 0; i < 10000000; i++ {
a += i
}
fmt.Println(index, a)
c <- true
}
```
求解。
还是七楼优雅,利用了close的特性。如果wg的代码放在一起,而不是“defer wg.Done()"放在Go函数中,就更符合习惯。需调整部分:
```Go
//...
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
Go(c, i) // 内部的Defer ..,需要删除
wg.Done()
}()
}
wg.Wait()
close(c)
//...
```
#8
更多评论
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