【go从入门到精通】精通并发编程-channel

warning: 这篇文章距离上次修改已过189天,其中的内容可能已经有所变动。

在Go语言中,并发和通信是密切相关的。channel是Go中实现并发通信的主要方式。

一、channel的定义和使用

Go语言中的通道类型(channel)允许Goroutine之间通过它们进行通信。通道是线程安全的,可以用于传递不同类型的数据。

定义一个channel:




var channel chan int

创建一个channel:




channel := make(chan int)

向channel发送数据:




channel <- 10

从channel接收数据:




value := <-channel

二、channel的不同使用方式

  1. 无缓冲的channel:

无缓冲的channel意味着发送和接收必须在两个goroutine同步之间进行。




package main
 
import (
    "fmt"
    "time"
)
 
func send(c chan int) {
    c <- 10
}
 
func main() {
    c := make(chan int)
    go send(c)
    fmt.Println(<-c)
}
  1. 有缓冲的channel:

有缓冲的channel可以存储一定数量的值,而不需要立即处理。




package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    c := make(chan int, 2)
    c <- 1
    c <- 2
    fmt.Println(<-c)
    fmt.Println(<-c)
}
  1. 使用for-range读取channel:



package main
 
import (
    "fmt"
    "time"
)
 
func send(c chan int) {
    for i := 0; i < 5; i++ {
        c <- i
    }
    close(c)
}
 
func main() {
    c := make(chan int)
    go send(c)
 
    for i := range c {
        fmt.Println(i)
    }
}
  1. 使用select处理多个channel:



package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    c1 := make(chan string)
    c2 := make(chan string)
 
    go func() {
        time.Sleep(2 * time.Second)
        c1 <- "one"
    }()
 
    go func() {
        time.Sleep(1 * time.Second)
        c2 <- "two"
    }()
 
    for i := 0; i < 2; i++ {
        select {
        case msg1 := <-c1:
            fmt.Println(msg1)
        case msg2 := <-c2:
            fmt.Println(msg2)
        }
    }
}

三、channel的关闭

可以使用内建的close函数来关闭channel。当一个channel被关闭,所有正在阻塞等待从该channel接收数据的goroutine都会收到一个0值。




package main
 
import (
    "fmt"
    "time"
)
 
func send(c chan int) {
    for i := 0; i < 5; i++ {
        c <- i
    }
    close(c)
}
 
func main() {
    c := make(chan int)
    go send(c)
 
    for {
        fmt.Println(<-c)
    }
}

在上面的代码中,我们尝试从关闭的channel中接收数据,当所有的数据都被接收后,再尝试接收会返回0值,并且一直阻塞下去。所以,我们可以通过检查接收操作的第二个返回值来判断

最后修改于:2024年08月17日 20:06

评论已关闭

推荐阅读

DDPG 模型解析,附Pytorch完整代码
2024年11月24日
DQN 模型解析,附Pytorch完整代码
2024年11月24日
AIGC实战——Transformer模型
2024年12月01日
Socket TCP 和 UDP 编程基础(Python)
2024年11月30日
python , tcp , udp
如何使用 ChatGPT 进行学术润色?你需要这些指令
2024年12月01日
AI
最新 Python 调用 OpenAi 详细教程实现问答、图像合成、图像理解、语音合成、语音识别(详细教程)
2024年11月24日
ChatGPT 和 DALL·E 2 配合生成故事绘本
2024年12月01日
omegaconf,一个超强的 Python 库!
2024年11月24日
【视觉AIGC识别】误差特征、人脸伪造检测、其他类型假图检测
2024年12月01日
[超级详细]如何在深度学习训练模型过程中使用 GPU 加速
2024年11月29日
Python 物理引擎pymunk最完整教程
2024年11月27日
MediaPipe 人体姿态与手指关键点检测教程
2024年11月27日
深入了解 Taipy:Python 打造 Web 应用的全面教程
2024年11月26日
基于Transformer的时间序列预测模型
2024年11月25日
Python在金融大数据分析中的AI应用(股价分析、量化交易)实战
2024年11月25日
AIGC Gradio系列学习教程之Components
2024年12月01日
Python3 `asyncio` — 异步 I/O,事件循环和并发工具
2024年11月30日
llama-factory SFT系列教程:大模型在自定义数据集 LoRA 训练与部署
2024年12月01日
Python 多线程和多进程用法
2024年11月24日
Python socket详解,全网最全教程
2024年11月27日