package main
import (
"fmt"
)
var (
numChan = make(chan int,10)
resChan = make(chan map[int]int,8)
exitChan = make(chan bool,8)
)
func main(){
//1 协程 存放数字
go func(){
for i:=1;i<=2000;i++{
numChan<-i
}
close(numChan)
}()
// 8 协程 取 计算1+...+n的值 存到另一个管道 resChan
for i:=0;i<8;i++{
go func(){
for;;{
n= <-numChan
// 该协程取完了
if len(numChan)== 0{
break
}
// 计算 n连加 = sum
sum:=0
for j:=0;j<n;j++{
sum+=n
}
// 存到另一个管道 resChan
resSlice := make(map[int]int)
resSlice[n] = sum
resChan<-resSlice
}
exitChan<-true
}()
}
go func(){
for;;{
if len(exitChan) == 8{
close(resChan)
// close(exitChan) //可关可不关
break
}
}
}()
// 遍历 resChen 打印
for v :=range resChan{
for index,value:=range v{
fmt.Printf("res[%v] = %v\n",index,value)
}
}
}
goruntine+channel 案例练习一
最新推荐文章于 2024-03-21 09:17:14 发布