24

Go语言中channel的基础知识

 5 years ago
source link: https://studygolang.com/articles/15299?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

channel

goroutine 运行在相同的地址空间,因此访问共享内存必须做好同步。 goroutine 奉行 通过通信来共享内存,而不是共享内存来通信

引⽤类型 channel CSP 模式的具体实现,用于多个 goroutine 通讯。其内部实现了同步,确保并发安全。

  channel 类型

map 类似, channel 也一个对应 make 创建的底层数据结构的引用。

当我们复制一个 channel 或用于函数参数传递时,我们只是拷贝了一个 channel 引用,因此调用者何被调用者将引用同一个 channel 对象。和其它的引用类型一样, channel 的零值也是 nil

定义一个 channel 时,也需要定义发送到 channel 的值的类型。 channel 可以使用内置的 make() 函数来创建:

make ( chan   Type )   // 等价于 make(chan   Type,   0)

make ( chan   Type ,   capacity )

capacity = 0 时, channel 是无缓冲阻塞读写的,当 capacity > 0 时, channel 有缓冲、是非阻塞的,直到写满 capacity 个元素才阻塞写入。

channel 通过操作符 <- 来接收和发送数据,发送和接收数据语法:

channel   <-   value         // 发送 value channel

<- channel               // 接收并将其丢弃

x   :=   <- channel          // channel 中接收数据,并赋值给 x

x ,   ok   :=   <- channel      // 功能同上,同时检查通道是否已关闭或者是否为空

默认情况下, channel 接收和发送数据都是阻塞的,除非另一端已经准备好,这样就使得 goroutine 同步变的更加的简单,而不需要显式的 lock


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK