代码如下:
```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
}
```
求解。
``` 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
更多评论
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