package main
import (
"fmt"
)
type Cat struct {
Name string
Age int
}
func writeData(intChan chan int) {
for i := 1; i <= 50; i++ {
//放入数据
intChan <- i
fmt.Println("writeData 读到=%v\n", i)
//time.Sleep(time.Second)
}
close(intChan) //关闭
}
//wirter data
func readData(intChan chan int, exitChan chan bool) {
for {
v, ok := <-intChan
if !ok {
break
}
fmt.Println("readData 读到=%v\n", v)
//time.Sleep(time.Second)
}
//readData 读取完数据后,即完任务
exitChan <- true
close(exitChan)
}
func main() {
//定义一个存放任意类型的管道,3个数据
// var allChan chan interface{}
/*allChan := make(chan interface{}, 3)
allChan <- 10
allChan <- "tom"
cat := Cat{"小花猫", 4}
allChan <- cat
//取第三个,丢掉前两个
<-allChan
<-allChan
newCat := <-allChan
fmt.Printf("newCat= %T, newCat=%v \n", newCat, newCat)*/
//intChan2 := make(chan int, 100)
//
//for i := 0; i < 100; i++ {
// intChan2 <- i * 2
//}
//
遍历,不能使用
///*for i := 0; i < len(intChan2); i++ {
//
//}*/
//
//for v := range intChan2 {
// fmt.Println("v=", v)
//}
//创建两个管道
intChan := make(chan int, 50)
exitChan := make(chan bool, 1)
go writeData(intChan)
go readData(intChan, exitChan)
//读退出的管道
for {
_, ok := <-exitChan
if !ok {
break
}
}
}
go 协程控制停止
最新推荐文章于 2024-07-15 10:44:28 发布