This is a creation in Article, where the information may have evolved or changed.
Description
The Channle in Golang is the main means of information interaction between the processes. Golang channel is divided into buffer and unbuffered two, about their usage differences can be self-Google, here no longer repeat. The channel reads and writes in Golang are synchronous semantics, and the full, read-empty channel will trigger the scheduling of the process.
Write data to the channel
Either unbuffered or buffered channel, when writing data to the channel to find that the channel is full, it is necessary to suspend the current write and schedule it once, and the current m to perform other threads within p. Until someone reads the channel again, it is discovered that there is a blocking wait for the write process to wake it up.
func chansend(t *chantype, c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool { ...... ...... // 对应缓冲区大小为0的channel if c.dataqsiz == 0 { // 如果有接收者在等着 // 这时候可以写入成功,将数据拷贝至 // 接收者的缓冲区,唤醒接收者即可 sg := c.recvq.dequeue() if sg != nil { ...... } // 如果尚未有接收者,需要将其block // no receiver available: block on this channel. gp := getg() mysg := acquireSudog() mysg.releasetime = 0 if t0 != 0 { mysg.releasetime = -1 } mysg.elem = ep mysg.waitlink = nil gp.waiting = mysg mysg.g = gp mysg.selectdone = nil gp.param = nil c.sendq.enqueue(mysg) // 在这里将发送者协程block goparkunlock(&c.lock, "chan send") } // 对于有缓冲区的channel,流程相似 ......}
If there are no receivers, then block the sender and call the function goparkunlock
Func Goparkunlock (lock *mutex, reason string) {Gopark (unsafe. Pointer (&parkunlock_c), unsafe. Pointer (lock), reason)}func Gopark (unlockf unsafe. Pointer, lock unsafe. Pointer, reason string) {mp: = Acquirem () GP: = Mp.curg Status: = Readgstatus (GP) if status! = _grunning & ;& Status! = _gscanrunning {gothrow ("Gopark:bad g Status")} Mp.waitlock = Lock MP.WAITUNLOCKF = UNL OCKF Gp.waitreason = Reason Releasem (MP)//FINAL Call function Park_m McAll (park_m)}void runtime park_m (G *GP) {bool OK ; First, the status of G is changed to Gwaiting runtime Casgstatus (GP, grunning, gwaiting); DROPG (); if (G->M->WAITUNLOCKF) {OK = G->M->WAITUNLOCKF (GP, G->m->waitlock); G->M->WAITUNLOCKF = nil; G->m->waitlock = nil; if (!ok) {Runtime Casgstatus (GP, gwaiting, grunnable); Execute (GP); Schedule it back, never returns. }}//Initiates a dispatch, the M no longer executes the current G, but chooses a new g to re-execute/ScheduleThe body implementation is not described here Schedule ();}
Reading data from the channel
Reading data from the channel and writing data to the channel is almost the same, only the direction is reversed, here no longer repeat, you delve into the code it.