1.channel分为2种 一种为有缓冲区 一种没有缓冲区
2.代码为 chan的结构定义
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 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
}
chan的发送和接收都是需要加锁的
3.无缓冲区的chan的发送过程
如图 发送操作总在对应的接收操作完成之前发送 而接收总发送在该通道进行发送前。
func main() {
c := make(chan int, 0)
c <- 1 //无论发送在前还是接收在前 都会报死锁
<-c
//time.Sleep(time.Microsecond)
}
所以接收和发送在同一个groutine中时 发送开始需要接收时需要接收开始为前提,发送结束需要保证接收结束 在同一个线程中无法同时满足条件。所以会死锁
func main() {
c := make(chan int, 1) //开启缓存区
c <- 1 //调换接收顺序会死锁
get := <-c
fmt.Println(get)
//time.Sleep(time.Microsecond)
}
开始缓冲区后只要满足前发送后接收就不会死锁