golang channel的介绍

Go语言中的channel是实现goroutine间无锁通信的关键机制,他使得写多线程并发程序变得简单、灵活、触手可得。

Channel是Go中的一个核心类型,你可以把它看成一个管道,通过它并发核心单元就可以发送或者接收数据进行通讯(communication)。

它的操作符是箭头 <- 。

ch <- v    // 发送值v到Channel ch中

v := <-ch  // 从Channel ch中接收数据,并将数据赋值给v

channel结构

type hchan struct {

qcount   uint           // total data in the queue 队列中存在的个数

dataqsiz uint           // size of the circular queue buffer大小 实现看起来是个循环数组

buf      unsafe.Pointer // points to an array of dataqsiz elements 数组指针

elemsize uint16       //channel类型的大小

closed   uint32      //channel是否关闭

elemtype *_type // element type //channel 类型

sendx    uint   // send index  //发送index

recvx    uint   // receive index //接收index

recvq    waitq  // list of recv waiters //接收链表 即读channel的goroutine

sendq    waitq  // list of send waiters //发送链表 即写channel的goroutine

// lock protects all fields in hchan, as well as several

// fields in sudogs blocked on this channel.

//

// Do not change another G's status while holding this lock

// (in particular, do not ready a G), as this can deadlock

// with stack shrinking.

lock mutex

}

本文来自php中文网的golang栏目:https://www.php.cn/be/go/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容