我需要通过创建x
0个Goroutine来增加x
个x
0倍,这将通过通道增加x
个.我该怎么做呢?
package main
import (
"fmt"
)
func main() {
var ch = make(chan int)
//1000 goroutines sending 1 through a channel
var x = 0
for i := 0; i < 1000; i++ {
go func() {
ch <- 1
}()
}
//Here i need to increase x by value read from the channel and then stop when the last value was sent
//But this code doesn't work
for {
if v, ok := <-ch; ok {
x += v
} else {
break
}
}
fmt.Println(x)
}
我想在最后关闭通道,但我不知道如何检测最后一个值是什么时候发送的