course/Concurrency/channel_practice.go

57 lines
972 B
Go
Raw Normal View History

package main
import (
"fmt"
"sync"
)
// channel练习
var WG sync.WaitGroup
// 1.启动一个goroutine生成100个数字发送到ch1
func set100Num(ch1 chan<- int) { //在声明后添加符号类型表示单向通道
defer WG.Done()
for i := 0; i < 100; i++ {
ch1 <- i
}
close(ch1)
}
// 2.启动一个goroutine从ch1中取值计算其平方放到ch2中
func get100Num(ch1 <-chan int, ch2 chan<- int) {
defer WG.Done()
for {
x, ok := <-ch1
if !ok {
break
}
ch2 <- x * x
}
close(ch2)
}
//3.在main函数中从ch2中取值打印出来
func main() {
e := make(chan int, 50)
f := make(chan int, 100)
WG.Add(2)
go set100Num(e)
go get100Num(e, f)
WG.Wait()
for ret := range f {
fmt.Printf("通道中数字的平方是:%v\n", ret)
}
ch3 := make(chan int, 2)
ch3 <- 10
ch3 <- 20
<-ch3
<-ch3
close(ch3) //取完值后关闭通道
t, ok := <-ch3
//第三次仍能取到
fmt.Println("第三此取出的值为", ok, t)
}