[Lecture du code source Golang1.20] runtime/chan.go

// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package runtime

// This file contains the implementation of Go channels.
// 此文件包含Go通道的实现。
// Invariants:
// 不变量:
//  At least one of c.sendq and c.recvq is empty,
//  except for the case of an unbuffered channel with a single goroutine
//  blocked on it for both sending and receiving using a select statement,
//  in which case the length of c.sendq and c.recvq is limited only by the
//  size of the select statement.
//  c.sendq和c.recvq中至少有一个是空的,除非是一个没有缓冲区的通道上有一个goroutine被阻塞,用于使用select语句进行发送和接收,
//  在这种情况下,c.sendq和c.recvq的长度仅受select语句的大小限制。
// For buffered channels, also:
// 对于缓冲通道,还应:
//  c.qcount > 0 implies that c.recvq is empty.
//  c.qcount < c.dataqsiz implies that c.sendq is empty.
// c.qcount>0表示c.recvq为空。
// c.qcount<c.dataqsiz意味着c.sendq为空。
import (
	"internal/abi"
	"runtime/internal/atomic"
	"runtime/internal/math"
	"unsafe"
)

const (
	maxAlign  = 8
	hchanSize = unsafe.Sizeof(hchan{}) + uintptr(-int(unsafe.Sizeof(hchan{}))&(maxAlign-1))
	debugChan = false
)

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 指向dataqsiz数组的指针
	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.
	// 锁保护hchan中的所有字段,以及在该通道上阻塞的sudogs中的几个字段。
	// 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.
	// 在持有该锁时,不要更改另一个G的状态(特别是,不要准备好一个G),因为这可能会导致堆栈收缩死锁。
	lock mutex
}

type waitq struct {
	first *sudog
	last  *sudog
}

//go:linkname reflect_makechan reflect.makechan
func reflect_makechan(t *chantype, size int) *hchan {
	return makechan(t, size)
}

func makechan64(t *chantype, size int64) *hchan {
	if int64(int(size)) != size {
		panic(plainError("makechan: size out of range"))
	}

	return makechan(t, int(size))
}

func makechan(t *chantype, size int) *hchan {
	elem := t.elem

	// compiler checks this but be safe.
	// 编译器对此进行检查,但要安全。
	if elem.size >= 1<<16 {
		throw("makechan: invalid channel element type")
	}
	if hchanSize%maxAlign != 0 || elem.align > maxAlign {
		throw("makechan: bad alignment")
	}

	mem, overflow := math.MulUintptr(elem.size, uintptr(size))
	if overflow || mem > maxAlloc-hchanSize || size < 0 {
		panic(plainError("makechan: size out of range"))
	}

	// Hchan does not contain pointers interesting for GC when elements stored in buf do not contain pointers.
	// buf points into the same allocation, elemtype is persistent.
	// SudoG's are referenced from their owning thread so they can't be collected.
	// TODO(dvyukov,rlh): Rethink when collector can move allocated objects.
	// 当存储在buf中的元素不包含指针时,Hchan不包含GC感兴趣的指针。buf指向相同的分配,elemtype是持久的。
	// SudoG是从其拥有的线程中引用的,因此无法收集它们。TODO(dvyukov,rlh):重新思考收集器何时可以移动已分配的对象。
	var c *hchan
	switch {
	case mem == 0:
		// Queue or element size is zero.
		// 队列或元素大小为零。
		c = (*hchan)(mallocgc(hchanSize, nil, true))
		// Race detector uses this location for synchronization.
		// 竞赛检测器使用此位置进行同步。
		c.buf = c.raceaddr()
	case elem.ptrdata == 0:
		// Elements do not contain pointers. 元素不包含指针。
		// Allocate hchan and buf in one call. 在一个调用中分配hchan和buf。
		c = (*hchan)(mallocgc(hchanSize+mem, nil, true))
		c.buf = add(unsafe.Pointer(c), hchanSize)
	default:
		// Elements contain pointers. 元素包含指针。
		c = new(hchan)
		c.buf = mallocgc(mem, elem, true)
	}

	c.elemsize = uint16(elem.size)
	c.elemtype = elem
	c.dataqsiz = uint(size)
	lockInit(&c.lock, lockRankHchan)

	if debugChan {
		print("makechan: chan=", c, "; elemsize=", elem.size, "; dataqsiz=", size, "\n")
	}
	return c
}

// chanbuf(c, i) is pointer to the i'th slot in the buffer.
// chanbuf(c,i)是指向缓冲区中第i个槽的指针。
func chanbuf(c *hchan, i uint) unsafe.Pointer {
	return add(c.buf, uintptr(i)*uintptr(c.elemsize))
}

// full reports whether a send on c would block (that is, the channel is full).
// It uses a single word-sized read of mutable state, so although
// the answer is instantaneously true, the correct answer may have changed
// by the time the calling function receives the return value.
// full报告c上的发送是否会阻塞(即通道已满)。
// 它使用可变状态的单个单词大小的读取,因此,尽管答案立即为true,但在调用函数接收到返回值时,正确的答案可能已经更改。
func full(c *hchan) bool {
	// c.dataqsiz is immutable (never written after the channel is created)
	// so it is safe to read at any time during channel operation.
	// c.dataqsiz是不可变的(在创建通道后从不写入),因此在通道操作期间的任何时候读取都是安全的。
	if c.dataqsiz == 0 {
		// Assumes that a pointer read is relaxed-atomic. 假设指针读取是松弛的原子。
		return c.recvq.first == nil
	}
	// Assumes that a uint read is relaxed-atomic. 假设一个uint读取是放松的原子。
	return c.qcount == c.dataqsiz
}

// entry point for c <- x from compiled code.
// 编译代码中c<-x的入口点。
//go:nosplit
func chansend1(c *hchan, elem unsafe.Pointer) {
	chansend(c, elem, true, getcallerpc())
}

/*
 * generic single channel send/recv
 * 通用单通道发送/接收
 * If block is not nil,
 * then the protocol will not
 * sleep but return if it could
 * not complete.
 * 如果块不是零,那么协议将不会休眠,但如果不能完成,则返回。
 * sleep can wake up with g.param == nil
 * when a channel involved in the sleep has
 * been closed.  it is easiest to loop and re-run
 * the operation; we'll see that it's now closed.
 * 当涉及睡眠的通道关闭时,sleep可以用g.param==nil唤醒。循环和重新运行操作是最容易的;我们会看到它现在已经关闭了。
 */
func chansend(c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool {
	if c == nil {
		if !block {
			return false
		}
		gopark(nil, nil, waitReasonChanSendNilChan, traceEvGoStop, 2)
		throw("unreachable")
	}

	if debugChan {
		print("chansend: chan=", c, "\n")
	}

	if raceenabled {
		racereadpc(c.raceaddr(), callerpc, abi.FuncPCABIInternal(chansend))
	}

	// Fast path: check for failed non-blocking operation without acquiring the lock.
	// 快速路径:在不获取锁的情况下检查失败的非阻塞操作。
	// After observing that the channel is not closed, we observe that the channel is
	// not ready for sending. Each of these observations is a single word-sized read
	// (first c.closed and second full()).
	// 在观察到通道没有关闭后,我们观察到通道还没有准备好发送。
	// 这些观察结果中的每一个都是一个单词大小的读数(第一个是c.closed,第二个是full())。

	// Because a closed channel cannot transition from 'ready for sending' to
	// 'not ready for sending', even if the channel is closed between the two observations,
	// they imply a moment between the two when the channel was both not yet closed
	// and not ready for sending. We behave as if we observed the channel at that moment,
	// and report that the send cannot proceed.
	// 由于闭合通道无法从“准备发送”转换为“未准备发送”,即使通道在两次观测之间闭合,它们也意味着通道尚未闭合且未准备发送。
	// 我们的行为就像当时观察到了通道,并报告发送无法继续。

	// It is okay if the reads are reordered here: if we observe that the channel is not
	// ready for sending and then observe that it is not closed, that implies that the
	// channel wasn't closed during the first observation. However, nothing here
	// guarantees forward progress. We rely on the side effects of lock release in
	// chanrecv() and closechan() to update this thread's view of c.closed and full().
	// 如果在这里重新排序读取,也没关系:如果我们观察到通道没有准备好发送,然后观察到它没有关闭,这意味着在第一次观察期间通道没有关闭。然而,这里没有任何东西可以保证取得进展。
	// 我们依靠chanrecv()和closechan()中释放锁的副作用来更新这个线程的c.closed和full()视图。
	if !block && c.closed == 0 && full(c) {
		return false
	}

	var t0 int64
	if blockprofilerate > 0 {
		t0 = cputicks()
	}

	lock(&c.lock)

	if c.closed != 0 {
		unlock(&c.lock)
		panic(plainError("send on closed channel"))
	}

	if sg := c.recvq.dequeue(); sg != nil {
		// Found a waiting receiver. We pass the value we want to send
		// directly to the receiver, bypassing the channel buffer (if any).
		// 发现一个正在等待的接收器。我们绕过通道缓冲区(如果有的话),将要发送的值直接传递给接收器。
		send(c, sg, ep, func() { unlock(&c.lock) }, 3)
		return true
	}

	if c.qcount < c.dataqsiz {
		// Space is available in the channel buffer. Enqueue the element to send.
		// 通道缓冲区中有可用空间。登记要发送的元素。
		qp := chanbuf(c, c.sendx)
		if raceenabled {
			racenotify(c, c.sendx, nil)
		}
		typedmemmove(c.elemtype, qp, ep)
		c.sendx++
		if c.sendx == c.dataqsiz {
			c.sendx = 0
		}
		c.qcount++
		unlock(&c.lock)
		return true
	}

	if !block {
		unlock(&c.lock)
		return false
	}

	// Block on the channel. Some receiver will complete our operation for us.
	// 阻塞通道。某个接收器将为我们完成操作。
	gp := getg()
	mysg := acquireSudog()
	mysg.releasetime = 0
	if t0 != 0 {
		mysg.releasetime = -1
	}
	// No stack splits between assigning elem and enqueuing mysg
	// on gp.waiting where copystack can find it.
	// 在分配elem和在gp.waiting上排队mysg之间没有堆栈分割,等待copystack可以找到它。
	mysg.elem = ep
	mysg.waitlink = nil
	mysg.g = gp
	mysg.isSelect = false
	mysg.c = c
	gp.waiting = mysg
	gp.param = nil
	c.sendq.enqueue(mysg)
	// Signal to anyone trying to shrink our stack that we're about
	// to park on a channel. The window between when this G's status
	// changes and when we set gp.activeStackChans is not safe for
	// stack shrinking.
	// 向任何试图缩小我们的堆栈的人发出信号,表明我们即将停在通道上。
	// 当这个G的状态改变时和我们设置gp.activeStackChans时之间的窗口对于堆栈收缩是不安全的。
	gp.parkingOnChan.Store(true)
	gopark(chanparkcommit, unsafe.Pointer(&c.lock), waitReasonChanSend, traceEvGoBlockSend, 2)
	// Ensure the value being sent is kept alive until the
	// receiver copies it out. The sudog has a pointer to the
	// stack object, but sudogs aren't considered as roots of the
	// stack tracer.
	// 确保发送的值保持活动状态,直到接收器将其复制出来。sudog有一个指向堆栈对象的指针,但sudog不被视为堆栈跟踪器的根。
	KeepAlive(ep)

	// someone woke us up.
	// 有人把我们唤醒了。
	if mysg != gp.waiting {
		throw("G waiting list is corrupted")
	}
	gp.waiting = nil
	gp.activeStackChans = false
	closed := !mysg.success
	gp.param = nil
	if mysg.releasetime > 0 {
		blockevent(mysg.releasetime-t0, 2)
	}
	mysg.c = nil
	releaseSudog(mysg)
	if closed {
		if c.closed == 0 {
			throw("chansend: spurious wakeup")
		}
		panic(plainError("send on closed channel"))
	}
	return true
}

// send processes a send operation on an empty channel c.
// send处理空通道c上的发送操作。
// The value ep sent by the sender is copied to the receiver sg.
// The receiver is then woken up to go on its merry way.
// Channel c must be empty and locked.  send unlocks c with unlockf.
// sg must already be dequeued from c.
// ep must be non-nil and point to the heap or the caller's stack.
// 发送器发送的值ep被复制到接收器sg。然后接收器被唤醒,继续它的快乐之路。通道c必须为空并锁定。
// send用unlockf解锁c。sg必须已经从c退出队列。ep必须是非nil并指向堆或调用方的堆栈。
func send(c *hchan, sg *sudog, ep unsafe.Pointer, unlockf func(), skip int) {
	if raceenabled {
		if c.dataqsiz == 0 {
			racesync(c, sg)
		} else {
			// Pretend we go through the buffer, even though
			// we copy directly. Note that we need to increment
			// the head/tail locations only when raceenabled.
			// 假设我们通过了缓冲区,即使我们直接复制。请注意,只有在启用race时,我们才需要增加头部/尾部位置。
			racenotify(c, c.recvx, nil)
			racenotify(c, c.recvx, sg)
			c.recvx++
			if c.recvx == c.dataqsiz {
				c.recvx = 0
			}
			c.sendx = c.recvx // c.sendx = (c.sendx+1) % c.dataqsiz
		}
	}
	if sg.elem != nil {
		sendDirect(c.elemtype, sg, ep)
		sg.elem = nil
	}
	gp := sg.g
	unlockf()
	gp.param = unsafe.Pointer(sg)
	sg.success = true
	if sg.releasetime != 0 {
		sg.releasetime = cputicks()
	}
	goready(gp, skip+1)
}

// Sends and receives on unbuffered or empty-buffered channels are the
// only operations where one running goroutine writes to the stack of
// another running goroutine. The GC assumes that stack writes only
// happen when the goroutine is running and are only done by that
// goroutine. Using a write barrier is sufficient to make up for
// violating that assumption, but the write barrier has to work.
// typedmemmove will call bulkBarrierPreWrite, but the target bytes
// are not in the heap, so that will not help. We arrange to call
// memmove and typeBitsBulkBarrier instead.
// 在无缓冲或空缓冲通道上发送和接收是一个运行goroutine写入另一个运行的goroutine的堆栈的唯一操作。
// GC假设堆栈写入仅在goroutine运行时发生,并且仅由该goroutine完成。使用写屏障足以弥补违反该假设的情况,但写屏障必须起作用。
// typedmemmove将调用bulkBarrierPreWrite,但目标字节不在堆中,所以这没有帮助。我们安排调用memmove并键入BitsBulkBarrier。
func sendDirect(t *_type, sg *sudog, src unsafe.Pointer) {
	// src is on our stack, dst is a slot on another stack.
	// src在我们的堆栈上,dst是另一个堆栈上的插槽。
	// Once we read sg.elem out of sg, it will no longer
	// be updated if the destination's stack gets copied (shrunk).
	// So make sure that no preemption points can happen between read & use.
	// 一旦我们从sg中读取sg.elem,如果目标堆栈被复制(收缩),它将不再更新。因此,请确保在读取和使用之间不会发生抢占点。
	dst := sg.elem
	typeBitsBulkBarrier(t, uintptr(dst), uintptr(src), t.size)
	// No need for cgo write barrier checks because dst is always
	// Go memory.
	// 无需进行cgo写入屏障检查,因为dst始终为Go内存。
	memmove(dst, src, t.size)
}

func recvDirect(t *_type, sg *sudog, dst unsafe.Pointer) {
	// dst is on our stack or the heap, src is on another stack.
	// The channel is locked, so src will not move during this
	// operation.
	// dst在我们的堆栈或堆上,src在另一个堆栈上。通道已锁定,因此src在此操作期间不会移动。
	src := sg.elem
	typeBitsBulkBarrier(t, uintptr(dst), uintptr(src), t.size)
	memmove(dst, src, t.size)
}

func closechan(c *hchan) {
	if c == nil {
		panic(plainError("close of nil channel"))
	}

	lock(&c.lock)
	if c.closed != 0 {
		unlock(&c.lock)
		panic(plainError("close of closed channel"))
	}

	if raceenabled {
		callerpc := getcallerpc()
		racewritepc(c.raceaddr(), callerpc, abi.FuncPCABIInternal(closechan))
		racerelease(c.raceaddr())
	}

	c.closed = 1

	var glist gList

	// release all readers 释放所有读取者
	for {
		sg := c.recvq.dequeue()
		if sg == nil {
			break
		}
		if sg.elem != nil {
			typedmemclr(c.elemtype, sg.elem)
			sg.elem = nil
		}
		if sg.releasetime != 0 {
			sg.releasetime = cputicks()
		}
		gp := sg.g
		gp.param = unsafe.Pointer(sg)
		sg.success = false
		if raceenabled {
			raceacquireg(gp, c.raceaddr())
		}
		glist.push(gp)
	}

	// release all writers (they will panic) 释放所有写入者(他们会惊慌失措)
	for {
		sg := c.sendq.dequeue()
		if sg == nil {
			break
		}
		sg.elem = nil
		if sg.releasetime != 0 {
			sg.releasetime = cputicks()
		}
		gp := sg.g
		gp.param = unsafe.Pointer(sg)
		sg.success = false
		if raceenabled {
			raceacquireg(gp, c.raceaddr())
		}
		glist.push(gp)
	}
	unlock(&c.lock)

	// Ready all Gs now that we've dropped the channel lock. 准备好所有的G,现在我们已经解除了通道锁定。
	for !glist.empty() {
		gp := glist.pop()
		gp.schedlink = 0
		goready(gp, 3)
	}
}

// empty reports whether a read from c would block (that is, the channel is
// empty).  It uses a single atomic read of mutable state.
// empty报告从c读取是否会阻塞(即通道为空)。它使用可变状态的单个原子读取。
func empty(c *hchan) bool {
	// c.dataqsiz is immutable.
	// c.dataqsiz是不可变的。
	if c.dataqsiz == 0 {
		return atomic.Loadp(unsafe.Pointer(&c.sendq.first)) == nil
	}
	return atomic.Loaduint(&c.qcount) == 0
}

// entry points for <- c from compiled code.
// 编译代码中<-c的入口点。
//go:nosplit
func chanrecv1(c *hchan, elem unsafe.Pointer) {
	chanrecv(c, elem, true)
}

//go:nosplit
func chanrecv2(c *hchan, elem unsafe.Pointer) (received bool) {
	_, received = chanrecv(c, elem, true)
	return
}

// chanrecv receives on channel c and writes the received data to ep.
// ep may be nil, in which case received data is ignored.
// If block == false and no elements are available, returns (false, false).
// Otherwise, if c is closed, zeros *ep and returns (true, false).
// Otherwise, fills in *ep with an element and returns (true, true).
// A non-nil ep must point to the heap or the caller's stack.
// chanrecv在通道c上接收并将接收到的数据写入ep。ep可以是nil,在这种情况下,接收到的数据被忽略。
// 如果block==false并且没有可用的元素,则返回(false,false)。否则,如果c是闭合的,则将*ep清零并返回(true,false)。
// 否则,在*ep中填充一个元素并返回(true,true)。非nil ep必须指向堆或调用方的堆栈。
func chanrecv(c *hchan, ep unsafe.Pointer, block bool) (selected, received bool) {
	// raceenabled: don't need to check ep, as it is always on the stack
	// or is new memory allocated by reflect.
	// raceenabled:不需要检查ep,因为它总是在堆栈上,或者是反射分配的新内存。
	if debugChan {
		print("chanrecv: chan=", c, "\n")
	}

	if c == nil {
		if !block {
			return
		}
		gopark(nil, nil, waitReasonChanReceiveNilChan, traceEvGoStop, 2)
		throw("unreachable")
	}

	// Fast path: check for failed non-blocking operation without acquiring the lock.
	// 快速路径:在不获取锁的情况下检查失败的非阻塞操作。
	if !block && empty(c) {
		// After observing that the channel is not ready for receiving, we observe whether the
		// channel is closed.
		// 在观察到通道没有准备好接收后,我们观察通道是否关闭。
		// Reordering of these checks could lead to incorrect behavior when racing with a close.
		// For example, if the channel was open and not empty, was closed, and then drained,
		// reordered reads could incorrectly indicate "open and empty". To prevent reordering,
		// we use atomic loads for both checks, and rely on emptying and closing to happen in
		// separate critical sections under the same lock.  This assumption fails when closing
		// an unbuffered channel with a blocked send, but that is an error condition anyway.
		// 重新排序这些检查可能会导致在比赛结束时出现错误行为。例如,如果通道是打开的而不是空的,是关闭的,然后排空,
		// 重新排序的读数可能会错误地指示“打开且空”。为了防止重新排序,我们对这两种检查都使用原子加载,并依靠清空和关闭在同一锁下的不同关键部分中进行。
		// 当关闭一个发送阻塞的无缓冲通道时,这种假设失败了,但无论如何,这都是一种错误情况。
		if atomic.Load(&c.closed) == 0 {
			// Because a channel cannot be reopened, the later observation of the channel
			// being not closed implies that it was also not closed at the moment of the
			// first observation. We behave as if we observed the channel at that moment
			// and report that the receive cannot proceed.
			// 由于通道无法重新打开,因此后来对通道未关闭的观察表明,在第一次观察时,通道也未关闭。我们表现得好像在那一刻观察到了频道,并报告接收无法继续。
			return
		}
		// The channel is irreversibly closed. Re-check whether the channel has any pending data
		// to receive, which could have arrived between the empty and closed checks above.
		// Sequential consistency is also required here, when racing with such a send.
		// 通道不可逆转地关闭。重新检查通道是否有任何待接收的数据,这些数据可能是在上述空检查和关闭检查之间到达的。当使用这样的发送进行比赛时,这里也需要顺序一致性。
		if empty(c) {
			// The channel is irreversibly closed and empty. 通道不可逆转地关闭和清空。
			if raceenabled {
				raceacquire(c.raceaddr())
			}
			if ep != nil {
				typedmemclr(c.elemtype, ep)
			}
			return true, false
		}
	}

	var t0 int64
	if blockprofilerate > 0 {
		t0 = cputicks()
	}

	lock(&c.lock)

	if c.closed != 0 {
		if c.qcount == 0 {
			if raceenabled {
				raceacquire(c.raceaddr())
			}
			unlock(&c.lock)
			if ep != nil {
				typedmemclr(c.elemtype, ep)
			}
			return true, false
		}
		// The channel has been closed, but the channel's buffer have data. 通道已关闭,但通道的缓冲区有数据。
	} else {
		// Just found waiting sender with not closed. 刚找到未关闭的正在等待的发件人。
		if sg := c.sendq.dequeue(); sg != nil {
			// Found a waiting sender. If buffer is size 0, receive value
			// directly from sender. Otherwise, receive from head of queue
			// and add sender's value to the tail of the queue (both map to
			// the same buffer slot because the queue is full).
			// 找到一个正在等待的发件人。如果缓冲区大小为0,则直接从发送方接收值。
			// 否则,从队列的头部接收并将发送方的值添加到队列的尾部(因为队列已满,所以两者都映射到同一个缓冲区插槽)。
			recv(c, sg, ep, func() { unlock(&c.lock) }, 3)
			return true, true
		}
	}

	if c.qcount > 0 {
		// Receive directly from queue 直接从队列接收
		qp := chanbuf(c, c.recvx)
		if raceenabled {
			racenotify(c, c.recvx, nil)
		}
		if ep != nil {
			typedmemmove(c.elemtype, ep, qp)
		}
		typedmemclr(c.elemtype, qp)
		c.recvx++
		if c.recvx == c.dataqsiz {
			c.recvx = 0
		}
		c.qcount--
		unlock(&c.lock)
		return true, true
	}

	if !block {
		unlock(&c.lock)
		return false, false
	}

	// no sender available: block on this channel. 没有可用的发送者:阻塞此通道。
	gp := getg()
	mysg := acquireSudog()
	mysg.releasetime = 0
	if t0 != 0 {
		mysg.releasetime = -1
	}
	// No stack splits between assigning elem and enqueuing mysg
	// on gp.waiting where copystack can find it.
	// 在分配elem和在gp.waiting上排队mysg之间没有堆栈分割,等待copystack可以找到它。
	mysg.elem = ep
	mysg.waitlink = nil
	gp.waiting = mysg
	mysg.g = gp
	mysg.isSelect = false
	mysg.c = c
	gp.param = nil
	c.recvq.enqueue(mysg)
	// Signal to anyone trying to shrink our stack that we're about
	// to park on a channel. The window between when this G's status
	// changes and when we set gp.activeStackChans is not safe for
	// stack shrinking.
	// 向任何试图缩小我们的堆栈的人发出信号,表明我们即将停在通道上。当这个G的状态改变时和我们设置gp.activeStackChans时之间的窗口对于堆栈收缩是不安全的。
	gp.parkingOnChan.Store(true)
	gopark(chanparkcommit, unsafe.Pointer(&c.lock), waitReasonChanReceive, traceEvGoBlockRecv, 2)

	// someone woke us up 有人把我们唤醒了
	if mysg != gp.waiting {
		throw("G waiting list is corrupted")
	}
	gp.waiting = nil
	gp.activeStackChans = false
	if mysg.releasetime > 0 {
		blockevent(mysg.releasetime-t0, 2)
	}
	success := mysg.success
	gp.param = nil
	mysg.c = nil
	releaseSudog(mysg)
	return true, success
}

// recv processes a receive operation on a full channel c.
// There are 2 parts:
//  1. The value sent by the sender sg is put into the channel
//     and the sender is woken up to go on its merry way.
//  2. The value received by the receiver (the current G) is
//     written to ep.
// recv处理全信道c上的接收操作。有两部分:
1.发送器sg发送的值被放入通道中,发送器被唤醒,继续它的快乐之路。
2.接收器接收到的值(当前G)被写入ep。
// For synchronous channels, both values are the same.
// For asynchronous channels, the receiver gets its data from
// the channel buffer and the sender's data is put in the
// channel buffer.
// Channel c must be full and locked. recv unlocks c with unlockf.
// sg must already be dequeued from c.
// A non-nil ep must point to the heap or the caller's stack.
// 对于同步通道,两个值相同。对于异步通道,接收器从通道缓冲区获取数据,发送器的数据被放入通道缓冲区。通道c必须已满并锁定。
// recv用unlock f解锁c。sg必须已经从c退出队列。非零ep必须指向堆或调用方的堆栈。
func recv(c *hchan, sg *sudog, ep unsafe.Pointer, unlockf func(), skip int) {
	if c.dataqsiz == 0 {
		if raceenabled {
			racesync(c, sg)
		}
		if ep != nil {
			// copy data from sender  从发送者复制数据
			recvDirect(c.elemtype, sg, ep)
		}
	} else {
		// Queue is full. Take the item at the
		// head of the queue. Make the sender enqueue
		// its item at the tail of the queue. Since the
		// queue is full, those are both the same slot.
		// 队列已满。拿队列最前面的项目。使发件人将其项目排入队列的尾部。由于队列已满,所以这两个都是同一个插槽。
		qp := chanbuf(c, c.recvx)
		if raceenabled {
			racenotify(c, c.recvx, nil)
			racenotify(c, c.recvx, sg)
		}
		// copy data from queue to receiver 将数据从队列复制到接收者
		if ep != nil {
			typedmemmove(c.elemtype, ep, qp)
		}
		// copy data from sender to queue 将数据从发送者复制到队列
		typedmemmove(c.elemtype, qp, sg.elem)
		c.recvx++
		if c.recvx == c.dataqsiz {
			c.recvx = 0
		}
		c.sendx = c.recvx // c.sendx = (c.sendx+1) % c.dataqsiz
	}
	sg.elem = nil
	gp := sg.g
	unlockf()
	gp.param = unsafe.Pointer(sg)
	sg.success = true
	if sg.releasetime != 0 {
		sg.releasetime = cputicks()
	}
	goready(gp, skip+1)
}

func chanparkcommit(gp *g, chanLock unsafe.Pointer) bool {
	// There are unlocked sudogs that point into gp's stack. Stack
	// copying must lock the channels of those sudogs.
	// Set activeStackChans here instead of before we try parking
	// because we could self-deadlock in stack growth on the
	// channel lock.
	// 有一些未锁定的sudog指向gp的堆栈。堆栈复制必须锁定那些sudog的通道。
	// 在这里设置activeStackChans,而不是在我们尝试停车之前,因为我们可能会在通道锁上的堆栈增长中自死锁。
	gp.activeStackChans = true
	// Mark that it's safe for stack shrinking to occur now,
	// because any thread acquiring this G's stack for shrinking
	// is guaranteed to observe activeStackChans after this store.
	// 标记现在发生堆栈收缩是安全的,因为任何获取该G的堆栈进行收缩的线程都保证在该存储之后观察activeStackChans。
	gp.parkingOnChan.Store(false)
	// Make sure we unlock after setting activeStackChans and
	// unsetting parkingOnChan. The moment we unlock chanLock
	// we risk gp getting readied by a channel operation and
	// so gp could continue running before everything before
	// the unlock is visible (even to gp itself).
	// 请确保我们在设置activeStackChans和取消设置parkingOnChan后解锁。解锁chanLock的那一刻,我们就有可能让gp为通道操作做好准备,因此gp可以在解锁可见之前(甚至对gp本身)继续运行。
	unlock((*mutex)(chanLock))
	return true
}

// compiler implements
// 编译器实现
//	select {
//	case c <- v:
//		... foo
//	default:
//		... bar
//	}
//
// as
//
//	if selectnbsend(c, v) {
//		... foo
//	} else {
//		... bar
//	}
func selectnbsend(c *hchan, elem unsafe.Pointer) (selected bool) {
	return chansend(c, elem, false, getcallerpc())
}

// compiler implements
// 编译器实现
//	select {
//	case v, ok = <-c:
//		... foo
//	default:
//		... bar
//	}
//
// as
//
//	if selected, ok = selectnbrecv(&v, c); selected {
//		... foo
//	} else {
//		... bar
//	}
func selectnbrecv(elem unsafe.Pointer, c *hchan) (selected, received bool) {
	return chanrecv(c, elem, false)
}

//go:linkname reflect_chansend reflect.chansend
func reflect_chansend(c *hchan, elem unsafe.Pointer, nb bool) (selected bool) {
	return chansend(c, elem, !nb, getcallerpc())
}

//go:linkname reflect_chanrecv reflect.chanrecv
func reflect_chanrecv(c *hchan, nb bool, elem unsafe.Pointer) (selected bool, received bool) {
	return chanrecv(c, elem, !nb)
}

//go:linkname reflect_chanlen reflect.chanlen
func reflect_chanlen(c *hchan) int {
	if c == nil {
		return 0
	}
	return int(c.qcount)
}

//go:linkname reflectlite_chanlen internal/reflectlite.chanlen
func reflectlite_chanlen(c *hchan) int {
	if c == nil {
		return 0
	}
	return int(c.qcount)
}

//go:linkname reflect_chancap reflect.chancap
func reflect_chancap(c *hchan) int {
	if c == nil {
		return 0
	}
	return int(c.dataqsiz)
}

//go:linkname reflect_chanclose reflect.chanclose
func reflect_chanclose(c *hchan) {
	closechan(c)
}

func (q *waitq) enqueue(sgp *sudog) {
	sgp.next = nil
	x := q.last
	if x == nil {
		sgp.prev = nil
		q.first = sgp
		q.last = sgp
		return
	}
	sgp.prev = x
	x.next = sgp
	q.last = sgp
}

func (q *waitq) dequeue() *sudog {
	for {
		sgp := q.first
		if sgp == nil {
			return nil
		}
		y := sgp.next
		if y == nil {
			q.first = nil
			q.last = nil
		} else {
			y.prev = nil
			q.first = y
			sgp.next = nil // mark as removed (see dequeueSudoG) 标记为已删除(请参阅dequeueSudoG)
		}

		// if a goroutine was put on this queue because of a
		// select, there is a small window between the goroutine
		// being woken up by a different case and it grabbing the
		// channel locks. Once it has the lock
		// it removes itself from the queue, so we won't see it after that.
		// We use a flag in the G struct to tell us when someone
		// else has won the race to signal this goroutine but the goroutine
		// hasn't removed itself from the queue yet.
		// 如果一个goroutine因为一个选择而被放在这个队列中,那么在被不同的情况唤醒的goroutine和它获取通道锁之间有一个小窗口。
		// 一旦它有了锁,它就会从队列中删除自己,所以在那之后我们就看不到它了。我们在G结构中使用一个标志来告诉我们,
		// 当其他人赢得了向这个goroutine发出信号的比赛时,但goroutine还没有从队列中删除自己。
		if sgp.isSelect && !sgp.g.selectDone.CompareAndSwap(0, 1) {
			continue
		}

		return sgp
	}
}

func (c *hchan) raceaddr() unsafe.Pointer {
	// Treat read-like and write-like operations on the channel to
	// happen at this address. Avoid using the address of qcount
	// or dataqsiz, because the len() and cap() builtins read
	// those addresses, and we don't want them racing with
	// operations like close().
	// 将通道上的类似读取和类似写入的操作视为在此地址发生。
	// 避免使用qcount或dataqsiz的地址,因为len()和cap()内置读取这些地址,我们不希望它们与close()等操作竞争。
	return unsafe.Pointer(&c.buf)
}

func racesync(c *hchan, sg *sudog) {
	racerelease(chanbuf(c, 0))
	raceacquireg(sg.g, chanbuf(c, 0))
	racereleaseg(sg.g, chanbuf(c, 0))
	raceacquire(chanbuf(c, 0))
}

// Notify the race detector of a send or receive involving buffer entry idx
// and a channel c or its communicating partner sg.
// This function handles the special case of c.elemsize==0.
// 将涉及缓冲区条目idx和通道c或其通信伙伴sg的发送或接收通知竞赛检测器。此函数处理c.elemsize==0的特殊情况。
func racenotify(c *hchan, idx uint, sg *sudog) {
	// We could have passed the unsafe.Pointer corresponding to entry idx
	// instead of idx itself.  However, in a future version of this function,
	// we can use idx to better handle the case of elemsize==0.
	// A future improvement to the detector is to call TSan with c and idx:
	// this way, Go will continue to not allocating buffer entries for channels
	// of elemsize==0, yet the race detector can be made to handle multiple
	// sync objects underneath the hood (one sync object per idx)
	// 我们本可以传递与条目idx相对应的unsafe.Pointer,而不是idx本身。然而,在这个函数的未来版本中,我们可以使用idx来更好地处理elemsize==0的情况。
	// 检测器的未来改进是用c和idx调用TSan:这样,Go将继续不为elemsize==0的通道分配缓冲区条目,但竞争检测器可以在引擎盖下处理多个同步对象(每个idx一个同步对象)
	qp := chanbuf(c, idx)
	// When elemsize==0, we don't allocate a full buffer for the channel.
	// Instead of individual buffer entries, the race detector uses the
	// c.buf as the only buffer entry.  This simplification prevents us from
	// following the memory model's happens-before rules (rules that are
	// implemented in racereleaseacquire).  Instead, we accumulate happens-before
	// information in the synchronization object associated with c.buf.
	// 当elemsize==0时,我们不会为通道分配完整的缓冲区。竞赛检测器使用c.buf作为唯一的缓冲区条目,而不是单个缓冲区条目。
	// 这种简化使我们无法遵循内存模型的先发生后规则(raceleaseacquire中实现的规则)。相反,我们在与c.buf关联的同步对象中积累发生在信息之前的信息。
	if c.elemsize == 0 {
		if sg == nil {
			raceacquire(qp)
			racerelease(qp)
		} else {
			raceacquireg(sg.g, qp)
			racereleaseg(sg.g, qp)
		}
	} else {
		if sg == nil {
			racereleaseacquire(qp)
		} else {
			racereleaseacquireg(sg.g, qp)
		}
	}
}

Guess you like

Origin blog.csdn.net/qq2942713658/article/details/132418790