1 回答
TA贡献1859条经验 获得超6个赞
问题是您将副本传递sync.WaitGroup给 goroutine,而不是引用(即指针):
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func main() {
numOfGoRoutines := 10
wg.Add(numOfGoRoutines)
ch := make(chan int, numOfGoRoutines)
for i := 0; i < numOfGoRoutines; i++ {
a := i
go sqr(ch, a, &wg)
}
wg.Wait()
fmt.Println("After WAIT")
close(ch)
var res int
for i := range ch {
res += i
}
ch = nil
fmt.Println("result = ", res)
}
func sqr(ch chan int, val int, wg *sync.WaitGroup) {
fmt.Println("go - ", val)
s := val * val
ch <- s
wg.Done()
}
此外,由于wg是一个全局变量,您可以完全删除该参数:
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func main() {
numOfGoRoutines := 10
wg.Add(numOfGoRoutines)
ch := make(chan int, numOfGoRoutines)
for i := 0; i < numOfGoRoutines; i++ {
a := i
go sqr(ch, a)
}
wg.Wait()
fmt.Println("After WAIT")
close(ch)
var res int
for i := range ch {
res += i
}
ch = nil
fmt.Println("result = ", res)
}
func sqr(ch chan int, val int) {
fmt.Println("go - ", val)
s := val * val
ch <- s
wg.Done()
}
- 1 回答
- 0 关注
- 177 浏览
添加回答
举报