美文网首页
go channel

go channel

作者: 心似南风 | 来源:发表于2020-09-15 11:33 被阅读0次

go version:1.12.5
文件 :src/runtime/chan.go

先分析下管道的结构体

type hchan struct {
    qcount   uint           // total data in the queue
    dataqsiz uint           // size of the circular queue
    buf      unsafe.Pointer // points to an array of dataqsiz elements
    elemsize uint16
    closed   uint32
    elemtype *_type // element type
    sendx    uint   // send index
    recvx    uint   // receive index
    recvq    waitq  // list of recv waiters
    sendq    waitq  // list of send waiters
    lock mutex
}
  • qcount
    当前队列中剩余的元素个数

  • dataqsize
    环形队列长度,即可以存放的元素个数

  • buf
    指向队列的内存,环形队列的指针

  • elemsize
    每个元素的大小

  • closed
    标识关闭状态

  • elemtype
    元素类型

  • sendx
    队列下标,指示元素写入时存放到队列中的位置,即队尾

  • recvx
    队列下标,指示下一个被读取的元素在队列中的位置,即队首

  • recvq
    等待读消息的协程队列,读取数据时,如果管道缓冲区为空或没有缓冲区,则当前协程会被阻塞,并被加入recvq队列.

  • sendq
    等待写消息的协程队列,向管道写入数据时,如果管道缓冲区已满或没有缓冲区,则当前协程会被阻塞,并被加入sendq队列.

  • lock mutex
    互斥锁, chan不允许并发读写,即一个管道同时仅允许被一个协程读写.

  • 注意: sendqrecvq中的至少一个为空,但使用select发送和接收的无缓冲通道上阻塞了单个goroutine的情况除外,在这种情况下,sendq的长度而recvq仅受select语句的大小限制.
    即:同一个协程使用select语句向管道一边写入一边读取,此时协程会分别位于两个队列
    qcount> 0表示recvq为空.
    qcount <dataqsiz表示sendq为空.

看图中结构体数据变化


image.png image.png

执行逻辑

  • 向channel写入数据


    image.png
  • 从channel中读取数据


    image.png

参考《GO专家编程》

相关文章

  • 文章收藏

    channel Go Channel 详解

  • Golang Channel底层实现

    Go Channel 底层实现 目录 channel 是什么 channel 的创建 channel 的发送 ch...

  • 26.Go语言·管道Channel

    main.go model/Channel.go

  • Go语言——channel详解

    Go语言——channel详解 channel和goroutine是go语言最具特色是结构,有必要仔细研究。 源码...

  • channel in Go's runtime

    http://skoo.me/go/2013/09/20/go-runtime-channel/

  • Go channel

    单纯地将函数并发执行是没有意义的,函数与函数之间需要交换数据才能体现并发执行函数的作用。虽然可使用共享内存进行数据...

  • go channel

    [toc] Channel 编译器翻译 关键数据结构 hchan sudog hchan sudog 其中buf ...

  • go channel

    浅析 go channel channel 是 goroutine 之间通信的一种方式,可以类比成 Unix 中的...

  • go channel

    channel channel一般用于goroutine之间的通信;初始化chan :=make(chan int...

  • Go - Channel

    设计理念 执行业务处理的 goroutine 不要通过共享内存的方式通信,而是要通过 Channel 通信的方式分...

网友评论

      本文标题:go channel

      本文链接:https://www.haomeiwen.com/subject/qdllektx.html