首先引用一句名言:
Don’t communicate by sharing memory; share memory by communicating.
(不要通过共享内存来通信,而应该通过通信来共享内存。)-Rob Pike
我是这样理解的:
1 简介
通道(chan)类似于一个队列,特性就是先进先出,多用于goruntine之间的通信
声明方式:
代码语言:go复制ch := make(chan int)
放入元素:
代码语言:go复制ch <- 0
取出元素:
代码语言:go复制elem1 := <-ch
遍历元素:
代码语言:go复制for data := range ch {
...
}
2 最基本使用
代码语言:go复制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: %vn", elem1)
fmt.Printf("The first element received from channel ch1: %vn", elem2)
fmt.Printf("The first element received from channel ch1: %vn", elem3)
//关闭通道
close(ch1)
}
3 引入panic()方法
代码语言:go复制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: %vn", elem1)
fmt.Printf("The first element received from channel ch1: %vn", elem2)
//panic内置函数停止当前线程的正常执行goroutine
panic(ch1)
fmt.Printf("The first element received from channel ch1: %vn", elem3)
//关闭通道
close(ch1)
}
4 不同协程间通信
代码语言:go复制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
}
}
}
我正在参与2023腾讯技术创作特训营第二期有奖征文,瓜分万元奖池和键盘手表