引出channel
channel的基本介绍
channel的基本使用
注意事项
1.具体代码(不关闭channel)
package main
import (
"fmt"
)
type Fact struct{
Num int // n
Factorial int // n的阶乘
}
func caltulateFactorial(myChan chan Fact, n int){
res := 1
for i:=1;i<=n;i++{
res *= i
}
var f Fact = Fact{n, res}
myChan<- f
}
func main(){
var myChan = make(chan Fact, 20)
var f Fact = Fact{}
// 开启20个协程
for i:=1;i<=20;i++{
go caltulateFactorial(myChan, i)
}
// 输出结果
for i:=1;i<=20;i++{
f = <-myChan
fmt.Println(f.Num,"的阶乘 =", f.Factorial)
}
}
2.具体代码(关闭channel)
package main
import (
"fmt"
)
type Fact struct{
Num int // n
Factorial int // n的阶乘
}
func caltulateFactorial(myChan chan Fact, boolChan chan bool, n int){
res := 1
for i:=1;i<=n;i++{
res *= i
}
var f Fact = Fact{n, res}
myChan<- f
boolChan<- true
}
func main(){
var myChan = make(chan Fact, 20)
var boolChan = make(chan bool, 20)
// 开启20个协程
for i:=1;i<=20;i++{
go caltulateFactorial(myChan, boolChan, i)
}
go func(){
for i:=0;i<20;i++{
<-boolChan // 每次取一个,都取出则说明20个协程都执行完毕
}
close(myChan)// 此时关闭myChan
}()
// 输出结果
// 因为已经关闭了channel,所以可以用for-range来遍历,否则会报错
for val := range myChan{
fmt.Println(val.Num,"的阶乘 =", val.Factorial)
}
}
结果