0
点赞
收藏
分享

微信扫一扫

深入浅出Go语言通道chan类型


首先引用一句名言:


Don’t communicate by sharing memory; share memory by communicating.

(不要通过共享内存来通信,而应该通过通信来共享内存。)-Rob Pike


我是这样理解的:

深入浅出Go语言通道chan类型_redis

1 简介

通道(chan)类似于一个队列,特性就是先进先出,多用于goruntine之间的通信

声明方式:

ch := make(chan int)

放入元素:

ch <- 0

取出元素:

elem1 := <-ch

遍历元素:

for data := range ch {
...
}

2 最基本使用

func chanPlay01() {
//声明一个chan,设置长度为3
ch1 := make(chan int, 3)
//进channel
ch1 <- 2
ch1 <- 1
ch1 <- 3
//出channel
elem1 := <-ch1
elem2 := <-ch1
elem3 := <-ch1
//打印通道的值
fmt.Printf("The first element received from channel ch1: %v\n", elem1)
fmt.Printf("The first element received from channel ch1: %v\n", elem2)
fmt.Printf("The first element received from channel ch1: %v\n", elem3)
//关闭通道
close(ch1)
}

3 引入panic()方法

func chanPlay03() {
//声明一个chan,设置长度为3
ch1 := make(chan int, 2)
//进channel
ch1 <- 2
ch1 <- 1
ch1 <- 3
//出channel
elem1 := <-ch1
elem2 := <-ch1
elem3 := <-ch1
//打印通道的值
fmt.Printf("The first element received from channel ch1: %v\n", elem1)
fmt.Printf("The first element received from channel ch1: %v\n", elem2)
//panic内置函数停止当前线程的正常执行goroutine
panic(ch1)
fmt.Printf("The first element received from channel ch1: %v\n", elem3)
//关闭通道
close(ch1)
}

4 不同协程间通信

func main() {
// 构建一个通道
ch := make(chan int)
// 开启一个并发匿名函数
go func() {
// 从3循环到0
for i := 3; i >= 0; i-- {
// 发送3到0之间的数值
ch <- i
// 每次发送完时等待
time.Sleep(time.Second)
}
}()
// 遍历接收通道数据
for data := range ch {
// 打印通道数据
fmt.Println(data)
// 当遇到数据0时, 退出接收循环
if data == 0 {
break
}
}
}



举报

相关推荐

0 条评论