//要求:1.将1~2000个数放入一个ch中 2.启动8个协程读取该ch,并计算1~n之和写入reschan中
```go
func InitNum(ch chan int) {
for i := 1; i <= 2000; i++ {
ch <- i
}
close(ch)
}
func readNum(ch chan int, reschan chan map[int]int, remap chan bool) {
for {
temp, ok := <-ch
if !ok {
break
} else {
res := 0
remp1 := make(map[int]int)
for i := 1; i <= temp; i++ {
res = res + i
}
remp1[temp] = res
reschan <- remp1
}
}
}
func readMap(reschan chan map[int]int, remap chan bool) {
for {
temp, ok := <-reschan
if !ok {
fmt.Println("readMap break")
break
} else {
fmt.Println(temp)
}
}
remap <- true
close(remap)
}
func main() {
ch := make(chan int, 2000)
reschan := make(chan map[int]int, 2000)
remap := make(chan bool, 8)
for i := 0; i < 8; i++ {
go readNum(ch, reschan, remap)
go readMap(reschan, remap)
}
go InitNum(ch)
for i := 0; i < 8; i++ {
<-remap
}
}
```
有疑问加站长微信联系(非本文作者)