1 回答
TA贡献1831条经验 获得超9个赞
有,runtime.NumGoroutine但你接近这个错误。
您的循环将不断产生 goroutine。
由于 for 循环,这将不必要地消耗 CPU 周期。
一种方法是使用sync.WaitGroup。
func deen(wg *sync.WaitGroup, queue chan int) {
for element := range queue {
fmt.Println("element is ", element)
if element%2 == 0 {
fmt.Println("new element is ", element)
wg.Add(2)
queue <- (element*100 + 11)
queue <- (element*100 + 33)
}
wg.Done()
}
}
func main() {
var wg sync.WaitGroup
queue := make(chan int, 10)
queue <- 1
queue <- 2
queue <- 3
queue <- 0
for i := 0; i < 4; i++ {
wg.Add(1)
go deen(&wg, queue)
}
wg.Wait()
close(queue)
fmt.Println("list len", len(queue)) //this must be 0
}
playground
--- 带有比赛的旧越野车版本---
func deen(wg *sync.WaitGroup, queue chan int) {
for element := range queue {
wg.Done()
fmt.Println("element is ", element)
if element%2 == 0 {
fmt.Println("new element is ", element)
wg.Add(2)
queue <- (element*100 + 11)
queue <- (element*100 + 33)
}
}
}
func main() {
var wg sync.WaitGroup
queue := make(chan int, 10)
queue <- 1
queue <- 2
queue <- 3
queue <- 0
for i := 0; i < 4; i++ {
wg.Add(1)
go deen(&wg, queue)
}
wg.Wait()
close(queue)
fmt.Println("list is has len", len(queue)) //this must be 0
}
- 1 回答
- 0 关注
- 240 浏览
添加回答
举报