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 。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Art of Computer Programming, Volume 2
Knuth, Donald E. / Addison-Wesley Professional / 1997-11-04 / USD 79.99
Finally, after a wait of more than thirty-five years, the first part of Volume 4 is at last ready for publication. Check out the boxed set that brings together Volumes 1 - 4A in one elegant case, and ......一起来看看 《The Art of Computer Programming, Volume 2》 这本书的介绍吧!