2026-10-21 14:11:30 +08:00
<!DOCTYPE html>
< html lang = "zh-CN" data-theme = "light" >
< head >
< meta charset = "utf-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1" >
< title > 第 8 章 channel: CSP 的载体与并发编排 · Go 八股知识库< / title >
< meta name = "description" content = "从 CSP 与 hchan 结构讲起,拆开 channel 创建、收发三条路径与 close 的唤醒逻辑,讲透 select 的随机与加锁顺序,并给出 0/1/N/信号量/worker pool 的容量设计、常见模式、泄漏排查与 channel/mutex 取舍。" >
< link rel = "stylesheet" href = "assets/doc.css" >
< / head >
< body >
< header class = "topbar" >
< div class = "tb-in" >
< a class = "brand" href = "index.html" > < span class = "logo" > GO< / span > < div > Go 八股< small > 从运行时原理到面试表达< / small > < / div > < / a >
< div class = "crumbs" >
< a href = "index.html" > 总目录< / a > < span class = "sep" > /< / span > < b > 第 8 章< / b >
< / div >
< div class = "spacer" > < / div >
< button class = "btn" id = "tocToggle" > ☰ 导航< / button >
< button class = "btn" id = "themeBtn" title = "切换到深色主题" > 深色< / button >
< / div >
< / header >
< div class = "layout" id = "layout" >
< aside class = "sidebar" >
< h2 > 章节目录< / h2 >
< nav id = "chapters" > < a class = "toc-a" href = "01-goroutine.html" > < i class = "cn" > 1< / i > 从进程到 goroutine: 并发模型的底层账本< / a > < a class = "toc-a" href = "02-gmp.html" > < i class = "cn" > 2< / i > GMP 调度器: Go 如何把十万个 goroutine 跑起来< / a > < a class = "toc-a" href = "03-memory.html" > < i class = "cn" > 3< / i > 内存分配:从 mspan 到 mallocgc< / a > < a class = "toc-a" href = "04-gc-mark.html" > < i class = "cn" > 4< / i > 垃圾回收(上):三色标记与写屏障< / a > < a class = "toc-a" href = "05-gc-source.html" > < i class = "cn" > 5< / i > 垃圾回收(下):一次 GC 的完整生命周期< / a > < a class = "toc-a" href = "06-slice.html" > < i class = "cn" > 6< / i > slice: 视图、扩容与共享底层数组< / a > < a class = "toc-a" href = "07-map.html" > < i class = "cn" > 7< / i > map: 从 hmap/bmap 到 1.24 Swiss Table< / a > < span class = "toc-a active" aria-current = "page" > < i class = "cn" > 8< / i > channel: CSP 的载体与并发编排< / span > < div class = "subnav current" > < a class = "toc-a lv3" href = "#sec-8-1" > 8.1 CSP 与 channel 的定位< / a > < a class = "toc-a lv3" href = "#sec-8-2" > 8.2 hchan 结构: buf、sendq、recvq 与锁< / a > < a class = "toc-a lv3" href = "#sec-8-3" > 8.3 创建: makechan 与容量约束< / a > < a class = "toc-a lv3" href = "#sec-8-4" > 8.4 发送的三条路径< / a > < a class = "toc-a lv3" href = "#sec-8-5" > 8.5 接收的三条路径< / a > < a class = "toc-a lv3" href = "#sec-8-6" > 8.6 close 的语义与三个 panic< / a > < a class = "toc-a lv3" href = "#sec-8-7" > 8.7 select 的实现: pollorder 与 lockorder< / a > < a class = "toc-a lv3" href = "#sec-8-8" > 8.8 容量设计: 0、1、N、信号量与 worker pool< / a > < a class = "toc-a lv3" href = "#sec-8-9" > 8.9 常见模式:超时、取消、扇入扇出与泄漏< / a > < a class = "toc-a lv3" href = "#sec-8-10" > 8.10 channel 与锁的取舍< / a > < / div > < a class = "toc-a" href = "09-defer.html" > < i class = "cn" > 9< / i > defer、panic、recover 与闭包< / a > < a class = "toc-a" href = "10-sync.html" > < i class = "cn" > 10< / i > 锁与同步原语:从 Mutex 到 singleflight< / a > < a class = "toc-a" href = "11-context.html" > < i class = "cn" > 11< / i > context: 取消、超时与 goroutine 泄露防治< / a > < a class = "toc-a" href = "12-interface.html" > < i class = "cn" > 12< / i > 接口:隐式契约与运行时表示< / a > < a class = "toc-a" href = "13-puzzles.html" > < i class = "cn" > 13< / i > 并发编程题:从交替打印到 worker pool< / a > < a class = "toc-a" href = "14-interview.html" > < i class = "cn" > 14< / i > 面试速查:对比、版本演进与高频追问< / a > < / nav >
< div class = "side-foot" >
< a class = "btn" href = "index.html" > ← 总目录< / a >
< / div >
< / aside >
< div class = "mask" id = "mask" > < / div >
< main class = "main-col" >
< article >
< p class = "chapnav" >
< a href = "index.html" > Go 八股< / a >
< span > ·< / span >
< span > 第 < b class = "pos" > 8< / b > / 14 章< / span >
< / p >
< h2 id = "ch8" > < span class = "n" > 8< / span > channel: CSP 的载体与并发编排< / h2 >
2026-10-22 23:35:36 +08:00
< div class = "box ok" >
< span class = "bt" > 面试直答 · 30 秒版< / span >
2026-10-25 17:16:48 +08:00
< p > channel 是一把锁、一块环形缓冲、两张等待队列:等着发送的 goroutine 和等着接收的 goroutine, 各被包装成一个等待节点挂在对应队列上。< / p >
< p > 缓冲没满时,发送只做一次拷贝就返回;满了就把当前 goroutine 挂起。接收是镜像。关闭之后接收方拿到零值,< code > v, ok := < -ch< / code > 里那个 ok 用来区分「读到零值」和「channel 已关」。< / p >
2026-10-22 23:35:36 +08:00
< ul >
2026-10-25 17:16:48 +08:00
< li > 向已关闭的发、重复关闭、关闭 nil channel, 三件事都 panic, 所以关闭权只能给唯一的发送方。< / li >
< li > 无缓冲是纯同步点,有缓冲用来解耦和背压;容量是语义选择,不是性能旋钮。< / li >
< li > select 在多路就绪时随机选一个;阻塞的发送没配退出路径,就是一类泄漏。< / li >
2026-10-22 23:35:36 +08:00
< / ul >
< / div >
2026-10-21 14:11:30 +08:00
< div class = "lead" >
2026-10-25 17:16:48 +08:00
< b > 这一章解决什么:< / b > 人人会写 < code > ch < - v< / code > , 却少有人能说清「值到底拷了几次、goroutine 停在哪一步」。
这一章按「现象 → 机制 → 代价」重排:先拆开 channel 的结构体与环形缓冲,再走一遍收发的三条路径和 close 的唤醒逻辑,
然后讲 select 的两个顺序,最后落到容量设计与模式类泄漏。
< / div >
< h4 > 读之前:七个词< / h4 >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 词< / th > < th > 一句话< / th > < th > 在哪节< / th > < / tr > < / thead >
< tbody >
< tr > < td > 环形缓冲( buf) < / td > < td > 一块连续数组加两个游标,写满就绕回开头< / td > < td > 8.2< / td > < / tr >
< tr > < td > sendq / recvq< / td > < td > 挂着等发送、等接收的 goroutine 的两条链表< / td > < td > 8.2< / td > < / tr >
< tr > < td > 等待节点( sudog) < / td > < td > 一个阻塞 goroutine 的登记表:值拷到哪、挂在哪个 channel< / td > < td > 8.2< / td > < / tr >
< tr > < td > 直接交接< / td > < td > 不经缓冲,从一个变量拷到另一个变量,省掉缓冲那一步< / td > < td > 8.4 / 8.5< / td > < / tr >
< tr > < td > 会合( rendezvous) < / td > < td > 收发双方必须同时就绪才完成的同步点,即容量 0< / td > < td > 8.1< / td > < / tr >
< tr > < td > pollorder / lockorder< / td > < td > select 里「先检查谁」和「按什么顺序加锁」两个顺序< / td > < td > 8.7< / td > < / tr >
< tr > < td > 背压< / td > < td > 缓冲满了,让上游自己慢下来< / td > < td > 8.8< / td > < / tr >
< / tbody >
< / table >
< / div >
< div class = "box tip" >
< span class = "bt" > 怎么读这一章< / span >
< p > 每节都是「现象 → 机制 → 代价 → 一句话」。< b > 现象< / b > 都能自己跑出来,先看它;标了< b > 可跳过< / b > 的段落第一遍略过不影响主线;每节最后加粗那句是要背的。< b > 先看三张图< / b > : 环怎么转、发送走哪条路、select 的两张表。< / p >
2026-10-21 14:11:30 +08:00
< / div >
< h3 id = "sec-8-1" > 8.1 CSP 与 channel 的定位< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 同一段「发一个值」的代码,只把容量从 0 改成 1, 日志顺序就反过来: 容量 0 时先出现接收方的「收到」,再出现发送方的「发完」;容量 1 时发送方先返回,接收方才打印。改的只有两个字,差别却是「等对方」和「先存着」。< / p >
< p > < span class = "tag" > 机制< / span > 1978 年 Hoare 把输入输出提升为基本原语:并发单元各自顺序执行、只靠消息交互,于是「共享可变状态」这个前提被取消。落到 Go 上,口号不是禁止共享内存(锁一直都在),而是把「谁可以写」变成一次显式交接。< / p >
< p > 这次交接的实质是可见性:发送之前的写入,对完成接收的 goroutine 一定可见。所以 channel 首先是同步点,队列只是它的一种实现。< / p >
< p > 容量决定同步发生在哪一步。等于 0 时要收发碰面才算完成,是一次会合;大于 0 时同步只落在「未满/非空」这两个条件上,收发双方在时间上解耦。< b > 所以两者的区别是耦合程度,不是快慢。< / b > < / p >
< p > 「先挂起的先被服务」也是修出来的:早期实现靠「写缓冲 → 唤醒 → 抢读 → 失败再睡」的重试,带缓冲的 channel 并不严格先进先出( issue #11506) , 2015 年底改成直接交接,才有今天的语义。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box tip" >
< span class = "bt" > 面试怎么答「channel 是什么」< / span >
2026-10-25 17:16:48 +08:00
< p > 三句话一层:定位是 goroutine 之间的同步点,不只是队列;实现是带锁的环形队列加两条等待队列;取舍是传数据与编排用 channel, 保护状态用锁。先给这层, 再按追问展源码。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< p class = "take" > < b > 一句话:< / b > channel 传的是值和可见性两样东西;容量 0 是会合、容量 N 是解耦,两者都是语义决定,不是性能开关。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-8-2" > 8.2 hchan 结构: buf、sendq、recvq 与锁< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 打印 < code > unsafe.Sizeof(ch)< / code > 只有 8 字节,< code > cap(ch)< / code > 却可能是 6000——变量本身只是个指针, 容器另有其物。把缓冲塞满再多发一个, goroutine dump 里立刻多出一行停在 < code > chan send< / code > 的栈:多出来的不是内存,是一个被挂起的 goroutine。< / p >
< p > < span class = "tag" > 机制< / span > 真正的结构体在堆上,字段分三组:环形缓冲的游标、元素类型信息、两张等待队列,外加一把锁。< / p >
2026-10-21 15:21:43 +08:00
< pre data-lang = "go" data-name = "runtime/chan.go: hchan( Go 1.25 起, 12 个字段)" > type hchan struct {
2026-10-21 14:11:30 +08:00
qcount uint // 当前元素个数
dataqsiz uint // 环形缓冲长度,即 make 时的容量
buf unsafe.Pointer // 指向 dataqsiz 个元素的数组
elemsize uint16 // 元素大小,所以元素不能超过 64 KB
closed uint32 // 0=打开, 1=已关闭
2026-10-21 15:21:43 +08:00
timer *timer // 1.23 起:驱动这个 channel 的 timer
2026-10-21 14:11:30 +08:00
elemtype *_type // 元素类型, typedmemmove 与 GC 扫描要用
sendx uint // 下一个写入位置
recvx uint // 下一个读出位置
recvq waitq // 等待接收的 goroutine 队列
sendq waitq // 等待发送的 goroutine 队列
2026-10-21 15:21:43 +08:00
bubble *synctestBubble // 1.25 起: testing/synctest 的 bubble 归属
2026-10-21 14:11:30 +08:00
lock mutex // 保护上面所有字段
}< / pre >
2026-10-25 17:16:48 +08:00
< p > 缓冲是一块连续数组,第 i 个元素的地址是基址加 i 乘元素大小;下一个写的位置和下一个读的位置各是一个游标,走到容量就回绕。判空判满只看元素个数那个计数器——环里「空」和「满」的游标关系一模一样,必须有独立计数器才能区分。< / p >
< figure class = "figure" >
< svg viewBox = "0 0 720 340" role = "img" aria-label = "hchan 的缓冲是一个环:四个元素占着 0 到 3 格,写游标指向 4、读游标指向 0, 走到末尾就回绕, 空和满只看元素个数" >
< defs >
< marker id = "ar8a" markerWidth = "9" markerHeight = "9" refX = "7" refY = "3" orient = "auto" >
< path d = "M0,0 L7,3 L0,6 Z" style = "fill:var(--brand)" / >
< / marker >
< / defs >
< circle cx = "200" cy = "175" r = "95" style = "fill:none;stroke:var(--line);stroke-dasharray:4 6" / >
< rect x = "171" y = "62" width = "58" height = "36" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "200" y = "85" text-anchor = "middle" font-size = "12" style = "fill:var(--brand-ink)" > a0< / text >
< rect x = "253" y = "109" width = "58" height = "36" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "282" y = "132" text-anchor = "middle" font-size = "12" style = "fill:var(--brand-ink)" > a1< / text >
< rect x = "253" y = "205" width = "58" height = "36" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "282" y = "228" text-anchor = "middle" font-size = "12" style = "fill:var(--brand-ink)" > a2< / text >
< rect x = "171" y = "252" width = "58" height = "36" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "200" y = "275" text-anchor = "middle" font-size = "12" style = "fill:var(--brand-ink)" > a3< / text >
< rect x = "89" y = "205" width = "58" height = "36" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "118" y = "228" text-anchor = "middle" font-size = "12" style = "fill:var(--muted)" > 空< / text >
< rect x = "89" y = "109" width = "58" height = "36" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "118" y = "132" text-anchor = "middle" font-size = "12" style = "fill:var(--muted)" > 空< / text >
< text x = "200" y = "171" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > qcount = 4< / text >
< text x = "200" y = "193" text-anchor = "middle" font-size = "12.5" style = "fill:var(--muted)" > dataqsiz = 6< / text >
< text x = "200" y = "34" text-anchor = "middle" font-size = "12.5" style = "fill:var(--brand)" > recvx = 0 · 下一个要读< / text >
< path d = "M200,42 L200,58" style = "fill:none;stroke:var(--brand);stroke-width:1.6" marker-end = "url(#ar8a)" / >
< text x = "16" y = "312" font-size = "12.5" style = "fill:var(--brand)" > sendx = 4 · 下一个要写< / text >
< path d = "M96,300 L114,247" style = "fill:none;stroke:var(--brand);stroke-width:1.6" marker-end = "url(#ar8a)" / >
< text x = "350" y = "52" font-size = "12.5" style = "fill:var(--ink)" > buf 是一块连续数组< / text >
< text x = "350" y = "76" font-size = "12.5" style = "fill:var(--muted)" > 第 i 个元素 = buf + i × elemsize< / text >
< text x = "350" y = "112" font-size = "12.5" style = "fill:var(--ink)" > sendx: 下一个写入位< / text >
< text x = "350" y = "136" font-size = "12.5" style = "fill:var(--ink)" > recvx: 下一个读出位< / text >
< text x = "350" y = "160" font-size = "12.5" style = "fill:var(--muted)" > 走到末尾就回绕到 0< / text >
< text x = "350" y = "184" font-size = "12.5" style = "fill:var(--muted)" > 「环」只是取模,不是链表< / text >
< text x = "350" y = "224" font-size = "12.5" style = "fill:var(--ink)" > 空 / 满只看计数器:< / text >
< text x = "350" y = "248" font-size = "12.5" style = "fill:var(--muted)" > qcount == 0 → 空< / text >
< text x = "350" y = "272" font-size = "12.5" style = "fill:var(--muted)" > qcount == dataqsiz → 满< / text >
< / svg >
< div class = "figcap" > < b > 图 1< / b > · 缓冲是个环:游标走到末尾回绕,而「空」和「满」只能靠计数器区分< / div >
< / figure >
< p > 两张等待队列本质是一条双向链表,节点代表一个阻塞的 goroutine, 记着值该拷到哪个地址、挂在哪个 channel、这次是否成功; 节点从每个 P 的池里复用,所以 park 本身不需要重新分配。< / p >
< p > 关键一点:< b > 锁保护的是元数据,不保护元素< / b > 。计数器、游标、队列的修改,以及元素拷贝,都在锁内完成;但接收方拿到副本、解锁之后,对这个值的读写就与 channel 无关了。传指针时更明显:只保证指针值送达,不保证它指向的内容不被改。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box note" >
< span class = "bt" > 字段随版本略有增减< / span >
2026-10-21 15:21:43 +08:00
< p > Go 1.23 起 < code > hchan< / code > 多了 < code > timer *timer< / code > ; < b > 1.25 起< / b > 又多了
< code > bubble *synctestBubble< / code > ( < code > testing/synctest< / code > 在 1.25 GA) , 所以现在是
< strong > 12 个字段< / strong > (外加 < code > lock< / code > ) , 1.26 与 1.25 相同。面试按这 12 个答即可;
被追问「为什么顺序是这样」,答「这是< b > 源码里的声明顺序< / b > ,标量字段与指针字段是交错的
( < code > buf< / code > 、< code > timer< / code > 、< code > elemtype< / code > 、< code > recvq< / code > 、< code > sendq< / code > 、
< code > bubble< / code > 都是指针),照源码抄,别按记忆重排」。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< div class = "box warn" >
< span class = "bt" > 易错点 · < code > len(ch)< / code > 是快照,不是水位保证< / span >
< p > 它返回的是加锁那一刻的元素个数,读到的值下一纳秒就过期。用「长度为 0」判断「活干完了」会偶发漏判: 生产者可能还没发出第一个值, 也可能刚在解锁之后发出。要判结束只有两种可靠写法: 关闭加遍历, 或者自己维护一个显式计数。< / p >
< / div >
< p > < span class = "tag" > 代价< / span > 每次阻塞的收发都要一个等待节点加一次 park, 节点虽然从池里复用, 仍要清零、入队、出队; 整个 channel 只有一把锁,同一时刻所有收发都在这把锁上排队;元素至少拷一次,有缓冲时是两次。元素越大、并发越高,这把锁越像瓶颈。< / p >
< p class = "take" > < b > 一句话:< / b > channel 是「一把锁 + 一块环形数组 + 两张等待队列」,锁保护游标和队列,元素一拷完就与它无关。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-8-3" > 8.3 创建: makechan 与容量约束< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 给 channel 定义一个 64 KB 的元素类型: 编译能过, 运行时直接终止进程, recover 也抓不住——它不是 panic, 是运行时主动结束。反过来, < code > make(chan int, 10)< / code > 那一刻内存就已经分配好,不是等到第一次发送。< / p >
< p > < span class = "tag" > 机制< / span > 创建在编译期被改写成一次运行时调用,只做三件事:校验参数、算「元素大小 × 容量」、按元素是否含指针决定分配方式。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "runtime/chan.go: makechan( 简化) " > func makechan(t *chantype, size int) *hchan {
elem := t.Elem
if elem.Size_ > = 1< < 16 {
throw("makechan: invalid channel element type") // elemsize 是 uint16
}
mem, overflow := math.MulUintptr(elem.Size_, uintptr(size))
if overflow || mem > maxAlloc-hchanSize || size < 0 {
panic(plainError("makechan: size out of range"))
}
var c *hchan
switch {
case mem == 0: // 无缓冲,或元素是零大小类型
c = (*hchan)(mallocgc(hchanSize, nil, true))
c.buf = c.raceaddr() // 给 race detector 用的占位,不是真缓冲
case !elem.Pointers(): // 元素不含指针: hchan 与 buf 一次分配
c = (*hchan)(mallocgc(hchanSize+mem, nil, true))
c.buf = add(unsafe.Pointer(c), hchanSize)
default: // 元素含指针: buf 要按类型扫描,单独分配
c = new(hchan)
c.buf = mallocgc(mem, elem, true)
}
c.elemsize = uint16(elem.Size_)
c.elemtype = elem
c.dataqsiz = uint(size)
return c
}< / pre >
2026-10-25 17:16:48 +08:00
< p > 三个约束值得记住:元素类型必须小于 64 KB, 因为结构体里那个元素大小字段只有 16 位,装不下就直接 < code > throw< / code > ;容量为负、元素大小乘容量溢出、或超过堆的地址上限,都会 panic < code > makechan: size out of range< / code > 。< / p >
< p > < span class = "tag s" > 可跳过< / span > 分配策略是性能细节:元素不含指针时,结构体和缓冲区一次分配完,缓冲区紧跟在结构体后面,少一个 GC 对象;含指针时必须分开,因为缓冲区要按元素类型扫描。无论哪种,结构体都在堆上——返回的是指针,逃逸分析必然判它逃逸。< / p >
< div class = "box note" >
2026-10-21 14:11:30 +08:00
< span class = "bt" > 容量参数不要随手透传< / span >
2026-10-25 17:16:48 +08:00
< p > 常量负数在编译期就被拦下;但把外部传入的容量直接交给 < code > make< / code > ,运行期就会 panic。配置驱动的容量先做范围校验, 否则一个错配置能把服务启崩。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > 容量不是「预留」,是创建那一刻就按元素大小乘容量分配好的:< code > make(chan [1024]byte, 10000)< / code > 是 10 MB 立刻落账,一个值都没发也一样。元素越大,拷的字节越多,而有缓冲时一个值从发送方到接收方要经过两次拷贝。< / p >
< p class = "take" > < b > 一句话:< / b > 容量是「额度」不是「上限」——创建时就付清,元素大小则直接决定每次交接的拷贝成本。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-8-4" > 8.4 发送的三条路径< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 同一个 < code > ch < - v< / code > :在没有缓冲的 channel 上返回,意味着对方此刻一定已经拿到值;换成一个没写满的缓冲 channel, 发送方早就返回并继续跑, 接收方可能还在做上一件事。goroutine dump 里能直接看到这种不对称——一个在跑,另一个还没被调度。< / p >
< p > < span class = "tag" > 机制< / span > 发送被编译成一次运行时调用, 第一个参数是待发送值的地址, 第二个表明是否允许阻塞( select 里的非阻塞发送传 false) 。入口先加锁看是否已关闭, 然后按优先级在三件事里选一件。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "runtime/chan.go: chansend 的三条路径(简化)" > func chansend(c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool {
lock(& c.lock)
if c.closed != 0 {
unlock(& c.lock)
panic(plainError("send on closed channel"))
}
// ① 有等待的接收者:直接交接,跳过 buf
if sg := c.recvq.dequeue(); sg != nil {
send(c, sg, ep, func() { unlock(& c.lock) }, 3)
return true
}
// ② 缓冲区还有空位:拷进 buf[sendx]
if c.qcount < c.dataqsiz {
qp := chanbuf(c, c.sendx)
typedmemmove(c.elemtype, qp, ep)
c.sendx++
if c.sendx == c.dataqsiz {
c.sendx = 0
}
c.qcount++
unlock(& c.lock)
return true
}
// ③ 缓冲满且无人接收:自己挂到 sendq 上睡
if !block {
unlock(& c.lock)
return false
}
mysg := acquireSudog()
mysg.elem = ep
mysg.g = getg()
mysg.c = c
c.sendq.enqueue(mysg)
gopark(chanparkcommit, unsafe.Pointer(& c.lock), waitReasonChanSend, traceBlockChanSend, 2)
2026-10-25 12:54:18 +08:00
// 醒来后: success 为 false 表示 channel 已被关闭 —— 这里会 panic
if !mysg.success {
panic(plainError("send on closed channel"))
}
2026-10-21 14:11:30 +08:00
return true
}< / pre >
2026-10-25 17:16:48 +08:00
< figure class = "figure" >
< svg viewBox = "0 0 720 300" role = "img" aria-label = "发送的三条路径:有人在等就直接拷给对方,缓冲未满就拷进环形缓冲,缓冲已满就把自己挂到等待队列上睡下" >
< defs >
< marker id = "ar8b" markerWidth = "9" markerHeight = "9" refX = "7" refY = "3" orient = "auto" >
< path d = "M0,0 L7,3 L0,6 Z" style = "fill:var(--muted)" / >
< / marker >
< / defs >
< rect x = "16" y = "44" width = "150" height = "44" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "91" y = "72" text-anchor = "middle" font-size = "12.5" style = "fill:var(--brand-ink)" > ① 有接收者在等< / text >
< rect x = "188" y = "44" width = "150" height = "44" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "263" y = "72" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > 直接拷到对方变量< / text >
< rect x = "360" y = "44" width = "150" height = "44" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "435" y = "72" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > 唤醒并放进 runnext< / text >
< path d = "M170,66 L184,66" style = "fill:none;stroke:var(--muted);stroke-width:1.6" marker-end = "url(#ar8b)" / >
< path d = "M342,66 L356,66" style = "fill:none;stroke:var(--muted);stroke-width:1.6" marker-end = "url(#ar8b)" / >
< text x = "524" y = "62" font-size = "12.5" style = "fill:var(--muted)" > 不经过缓冲< / text >
< text x = "524" y = "82" font-size = "12.5" style = "fill:var(--muted)" > 一次拷贝就够< / text >
< rect x = "16" y = "136" width = "150" height = "44" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "91" y = "164" text-anchor = "middle" font-size = "12.5" style = "fill:var(--brand-ink)" > ② 缓冲未满< / text >
< rect x = "188" y = "136" width = "150" height = "44" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "263" y = "164" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > 拷进 buf 的下一个槽< / text >
< rect x = "360" y = "136" width = "150" height = "44" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "435" y = "164" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > 游标回绕,计数加一< / text >
< path d = "M170,158 L184,158" style = "fill:none;stroke:var(--muted);stroke-width:1.6" marker-end = "url(#ar8b)" / >
< path d = "M342,158 L356,158" style = "fill:none;stroke:var(--muted);stroke-width:1.6" marker-end = "url(#ar8b)" / >
< text x = "524" y = "154" font-size = "12.5" style = "fill:var(--muted)" > 全程不调度< / text >
< text x = "524" y = "174" font-size = "12.5" style = "fill:var(--muted)" > 最快的一条< / text >
< rect x = "16" y = "228" width = "150" height = "44" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "91" y = "256" text-anchor = "middle" font-size = "12.5" style = "fill:var(--brand-ink)" > ③ 缓冲满了< / text >
< rect x = "188" y = "228" width = "150" height = "44" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "263" y = "256" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > 建等待节点,挂上队列< / text >
< rect x = "360" y = "228" width = "150" height = "44" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "435" y = "256" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > gopark 睡下等对方< / text >
< path d = "M170,250 L184,250" style = "fill:none;stroke:var(--muted);stroke-width:1.6" marker-end = "url(#ar8b)" / >
< path d = "M342,250 L356,250" style = "fill:none;stroke:var(--muted);stroke-width:1.6" marker-end = "url(#ar8b)" / >
< text x = "524" y = "246" font-size = "12.5" style = "fill:var(--muted)" > 被 close 唤醒< / text >
< text x = "524" y = "266" font-size = "12.5" style = "fill:var(--muted)" > 则 panic< / text >
< / svg >
< div class = "figcap" > < b > 图 2< / b > · 发送的三条路径:能直接交接就不碰缓冲,碰了缓冲就不调度< / div >
< / figure >
< p > 路径 ① 的数据是发送方拷的:直接拷进接收方的变量地址,再把对方放回可运行队列;接收方一被唤醒,值已经就位。路径 ② 不涉及任何调度,只是持锁拷一次、挪一下游标。路径 ③ 把当前 goroutine 包成一个等待节点入队,然后 park; 真正睡下之前, 会有一次回调替它释放 channel 锁,否则别人永远叫不醒它。< / p >
< p > 无缓冲 channel 是 ① 与 ③ 的特例:容量为 0 让条件 ② 永远不成立,所以要么直接交给已等待的接收方,要么自己挂起等对方来取——这就是「无缓冲等于同步交接」的源码依据。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box note" >
< span class = "bt" > 为什么现在不需要「醒来重试」< / span >
2026-10-25 17:16:48 +08:00
< p > 早期实现是「写缓冲、唤醒、抢读、失败再睡」,靠重试完成交接,可能被后来者插队。现在接收方一次做两步:先把槽里的值拷给自己的接收变量,再把发送方的值填进< strong > 同一个槽< / strong > ,游标各自前移;被唤醒的发送方只收到一个「你的值已被取走」的通知。一次改动同时修好了先进先出与惊群。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< div class = "box warn" >
< span class = "bt" > 易错点 · 「发送成功」不等于「对方处理完了」< / span >
< p > 无缓冲 channel 的发送返回,只说明值已经到了对方的接收变量、对方已被唤醒——不代表它读完,更不代表处理完。缓冲 channel 连「对方是否收到」都不保证。所以别把发送成功当确认:要确认就另开一条回程 channel, 或者用 < code > WaitGroup< / code > 收尾。< / p >
< / div >
< p > < span class = "tag" > 代价< / span > 路径 ② 是持锁做一次内存拷贝,元素大时这段时间所有收发都在排队;路径 ③ 除拷贝外还要一次 park 与一次唤醒,量级是几十到几百纳秒,且 goroutine 越多、单锁的争抢越明显。< / p >
< p class = "take" > < b > 一句话:< / b > 发送只有三种下场——直接送到对方手上、进缓冲、睡下等;走了前两条就说明这次没有发生调度。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-8-5" > 8.5 接收的三条路径< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 一个没有发送方的 < code > < -ch< / code > 会一直卡着, goroutine dump 里停在 < code > chan receive< / code > ;同一行代码换成已关闭的 channel, 立刻就返回零值, 再也不会阻塞。同一句语法, 两种完全不同的时间行为。< / p >
< p > < span class = "tag" > 机制< / span > 接收被编译成一次运行时调用, 和一个「值收到哪里」的地址参数。那个地址可以是空——select 里只要事件、不取值的写法就传空,这时不拷贝内存,但游标和计数照常推进。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "runtime/chan.go: chanrecv 的三条路径(简化)" > func chanrecv(c *hchan, ep unsafe.Pointer, block bool) (selected, received bool) {
if c == nil { // nil channel: 永久阻塞( select 用它禁用分支)
if !block {
return
}
gopark(nil, nil, waitReasonChanReceiveNilChan, traceBlockForever, 2)
}
lock(& c.lock)
if c.closed != 0 & & c.qcount == 0 { // 已关闭且缓冲为空:给零值
unlock(& c.lock)
if ep != nil {
typedmemclr(c.elemtype, ep)
}
return true, false
}
// ① sendq 有等待的发送者
if sg := c.sendq.dequeue(); sg != nil {
recv(c, sg, ep, func() { unlock(& c.lock) }, 3)
return true, true
}
// ② 缓冲区有数据:从 buf[recvx] 取
if c.qcount > 0 {
qp := chanbuf(c, c.recvx)
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
}
// ③ 都空:自己进 recvq 睡
// ...
}< / pre >
2026-10-25 17:16:48 +08:00
< p > 路径 ① 的交接分两种:无缓冲时,把发送方的值直接拷给接收方;有缓冲时缓冲区一定是满的,于是先把 < code > buf[recvx]< / code > 拷给接收方,再把发送方的值填进同一个槽位,游标各自前移一格——队列仍然满,只是整体挪了一格。这就是「满了也不必搬整个队列」的技巧。< / p >
< p > 路径 ② 会额外把槽位清零。不清也能跑,但槽里残留的指针会被当成 GC 根,让本该回收的对象多活一轮。路径 ③ 醒来后靠节点上的成功标记区分:是拿到了数据,还是 channel 被关闭。< / p >
< p > < code > for v := range ch< / code > 就是反复接收, 直到「是否收到」为假才退出。所以「range 会在 close 后自动结束」不是语法糖,而是接收返回值驱动的循环。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box tip" >
< span class = "bt" > 大对象别直接塞进 channel< / span >
2026-10-25 17:16:48 +08:00
< p > 元素走 channel 至少拷两次( 发送方到缓冲, 缓冲到接收方) , 无缓冲时也是一次直接拷贝。要传大结构体就传指针, 但同时要想清楚所有权: channel 只保证指针送达,不保证它指向的内容之后不被改。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > 接收比发送多一笔清槽:取走之后要把槽位清零,元素含指针时这笔写不算小。真正的成本仍在拷贝次数上——有缓冲时一个值要搬两次,而「丢弃值」这条捷径只有 select 里不取值的写法才用得上。< / p >
< p class = "take" > < b > 一句话:< / b > 接收优先从等待的发送方直接拿, 其次从缓冲取, 都没有才睡下; close 让最后一种立刻变成「零值、不阻塞」。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-8-6" > 8.6 close 的语义与三个 panic< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 对着已关闭的 channel 再关一次, panic; 对着它发送, panic; 对着 nil 关,也 panic——三种崩法, 位置不同。而对着它接收却安静得很: 缓冲里的值先被吐完, 之后每次都是零值加 < code > ok=false< / code > ,读多少次都一样。< / p >
< p > < span class = "tag" > 机制< / span > close 编译成一次运行时调用,它要同时做两件事:把状态置成已关闭(之后所有发送路径都必须先看到这个标记),以及叫醒所有正在等这个 channel 的 goroutine。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "runtime/chan.go: closechan( 简化) " > 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"))
}
c.closed = 1
var glist gList
for { // 唤醒所有接收方:没有数据可给,给零值
sg := c.recvq.dequeue()
if sg == nil {
break
}
if sg.elem != nil {
typedmemclr(c.elemtype, sg.elem)
sg.elem = nil
}
sg.success = false
glist.push(sg.g)
}
for { // 唤醒所有发送方:它们醒来会 panic
sg := c.sendq.dequeue()
if sg == nil {
break
}
sg.elem = nil
sg.success = false
glist.push(sg.g)
}
unlock(& c.lock)
for !glist.empty() { // 解锁后再统一唤醒
gp := glist.pop()
gp.schedlink = 0
goready(gp, 3)
}
}< / pre >
2026-10-25 17:16:48 +08:00
< p > 四个动作:置关闭标记;遍历接收队列,把每个等待者的接收地址清零、标记为失败;遍历发送队列做同样的事(这些发送方醒来就会 panic) ; 最后解锁, 再统一把攒下来的 goroutine 逐个放回可运行队列。最后一步必须在解锁之后,否则被唤醒的人会立刻堵在同一把锁上。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "main.go: 关闭后的收发行为" > func main() {
ch := make(chan int, 2)
ch < - 1
ch < - 2
close(ch)
for i := 0; i < 3; i++ {
v, ok := < -ch
fmt.Println(v, ok)
}
defer func() { fmt.Println("recover:", recover()) }()
ch < - 3 // 向已关闭的 channel 发送
}< / pre >
< pre data-lang = "text" data-name = "输出( Go 1.26, amd64) " > 1 true
2 true
0 false
recover: send on closed channel< / pre >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 操作< / th > < th > nil channel< / th > < th > 打开< / th > < th > 已关闭< / th > < / tr > < / thead >
< tbody >
< tr > < td > < code > ch < - v< / code > < / td > < td > 永久阻塞< / td > < td > 正常或阻塞< / td > < td > panic: send on closed channel< / td > < / tr >
< tr > < td > < code > < -ch< / code > < / td > < td > 永久阻塞< / td > < td > 正常或阻塞< / td > < td > 先读完缓冲,之后零值与 < code > ok=false< / code > < / td > < / tr >
< tr > < td > < code > close(ch)< / code > < / td > < td > panic: close of nil channel< / td > < td > 正常,广播唤醒所有等待者< / td > < td > panic: close of closed channel< / td > < / tr >
< tr > < td > < code > len(ch)< / code > < / td > < td > 0< / td > < td > 当前缓冲元素数< / td > < td > 剩余元素数,仍可读完< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 17:16:48 +08:00
< div class = "box warn" >
< span class = "bt" > 易错点 · 关闭后读到的是零值,不是「读失败」< / span >
< p > 「关闭后读到零值」只在缓冲空时成立——缓冲里还有值时,会先按顺序读出来,那几个 < code > ok< / code > 仍然是 true。更常见的错误是拿值本身判断结束( < code > v == 0< / code > 或 < code > v == nil< / code > ):零值是合法数据,永远判不准。判断结束只能看第二个返回值,或者干脆用 range。< / p >
< / div >
< p > 工程规则只有一条:< strong > 发送方关闭< / strong > 。接收方不知道还有没有别的发送者在写,关掉就会让别人 panic; 多个发送方时用 < code > sync.Once< / code > 包一层,或者干脆不关、用额外的 < code > done< / code > channel 通知退出。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box danger" >
< span class = "bt" > 「谁创建谁关闭」的真正含义< / span >
< p > 不是「谁 make 谁 close」, 而是「谁拥有写端谁 close」。channel 传给下游读取方时,读的一方永远不该 close;
库代码里 channel 若是参数传进来的,通常由调用方关闭,库发完就返回。< / p >
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > close 要遍历两条等待队列,把每个节点都标记成失败,而且全程持锁;被唤醒的每个 goroutine 还要各自被调度一次。等待者越多,这一次 close 越贵——扇出一百个 goroutine 的池子,关闭就是一百次唤醒加一轮锁竞争。< / p >
< p class = "take" > < b > 一句话:< / b > close 是一次广播,不是一次发送:它表示「不会再有值了」,读的一方靠第二个返回值或 range 收尾,写的一方从此不许再写。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-8-7" > 8.7 select 的实现: pollorder 与 lockorder< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 两个 case 都就绪时,跑一万次看看谁被选中:次数大概各一半,没有「先写的优先」。可另一件事又与顺序有关——两个 goroutine 分别写 < code > select{a, b}< / code > 和 < code > select{b, a}< / code > ,程序不会因此死锁。说明「先检查哪个」和「先锁哪个」根本不是同一件事。< / p >
< p > < span class = "tag" > 机制< / span > select 被编译成一次运行时调用, case 先摊成一个描述符数组(每个只记 channel 和值的地址),然后由运行时生成两个顺序数组:一个决定检查次序,一个决定加锁次序。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "runtime/select.go: selectgo 的两个顺序(简化)" > // 1) pollorder: 随机打散, 决定「先检查哪个 case」
for i := range scases {
if scases[i].c == nil {
continue // nil channel 的 case 直接被跳过,等于禁用
}
j := cheaprandn(uint32(norder + 1)) // 插入式洗牌
pollorder[norder] = pollorder[j]
pollorder[j] = uint16(i)
norder++
}
// 2) lockorder: 按 hchan 地址全序堆排序,决定「按什么顺序加锁」
// (运行时手写 heapsort, 保证 n log n 与常数栈空间)
sellock(scases, lockorder) // 一次性锁住全部 channel
// 3) 按 pollorder 扫一遍找就绪的 case; 没有且有 default 就走 default
// 4) 否则把当前 G 的 sudog 挂到每个 channel 的等待队列上, gopark
// 5) 醒来后按 lockorder 把其它 channel 上的 sudog 逐个摘掉< / pre >
2026-10-25 17:16:48 +08:00
< figure class = "figure" >
< svg viewBox = "0 0 720 330" role = "img" aria-label = "同一个 select 的 case 集合有两套顺序:检查顺序被随机洗牌,加锁顺序按 channel 地址升序,前者保公平,后者防死锁" >
< text x = "40" y = "26" font-size = "12.5" style = "fill:var(--muted)" > 源码里写的 case 顺序< / text >
< rect x = "40" y = "40" width = "110" height = "36" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "95" y = "63" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > case 0< / text >
< rect x = "174" y = "40" width = "110" height = "36" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "229" y = "63" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > case 1< / text >
< rect x = "308" y = "40" width = "110" height = "36" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "363" y = "63" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > case 2< / text >
< rect x = "442" y = "40" width = "110" height = "36" rx = "8" style = "fill:var(--card);stroke:var(--line)" / >
< text x = "497" y = "63" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > case 3< / text >
< text x = "16" y = "118" font-size = "12.5" style = "fill:var(--ink)" > 检查顺序< / text >
< text x = "16" y = "136" font-size = "12.5" style = "fill:var(--muted)" > pollorder< / text >
< rect x = "170" y = "108" width = "100" height = "36" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "220" y = "131" text-anchor = "middle" font-size = "12.5" style = "fill:var(--brand-ink)" > ① case 2< / text >
< rect x = "286" y = "108" width = "100" height = "36" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "336" y = "131" text-anchor = "middle" font-size = "12.5" style = "fill:var(--brand-ink)" > ② case 0< / text >
< rect x = "402" y = "108" width = "100" height = "36" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "452" y = "131" text-anchor = "middle" font-size = "12.5" style = "fill:var(--brand-ink)" > ③ case 3< / text >
< rect x = "518" y = "108" width = "100" height = "36" rx = "8" style = "fill:var(--brand-soft);stroke:var(--brand)" / >
< text x = "568" y = "131" text-anchor = "middle" font-size = "12.5" style = "fill:var(--brand-ink)" > ④ case 1< / text >
< text x = "16" y = "208" font-size = "12.5" style = "fill:var(--ink)" > 加锁顺序< / text >
< text x = "16" y = "226" font-size = "12.5" style = "fill:var(--muted)" > lockorder< / text >
< rect x = "170" y = "198" width = "100" height = "36" rx = "8" style = "fill:var(--card);stroke:var(--brand)" / >
< text x = "220" y = "221" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > ① case 1< / text >
< rect x = "286" y = "198" width = "100" height = "36" rx = "8" style = "fill:var(--card);stroke:var(--brand)" / >
< text x = "336" y = "221" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > ② case 3< / text >
< rect x = "402" y = "198" width = "100" height = "36" rx = "8" style = "fill:var(--card);stroke:var(--brand)" / >
< text x = "452" y = "221" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > ③ case 0< / text >
< rect x = "518" y = "198" width = "100" height = "36" rx = "8" style = "fill:var(--card);stroke:var(--brand)" / >
< text x = "568" y = "221" text-anchor = "middle" font-size = "12.5" style = "fill:var(--ink)" > ④ case 2< / text >
< text x = "170" y = "160" font-size = "12" style = "fill:var(--muted)" > 每次运行都可能不同 → 保证公平< / text >
< text x = "170" y = "250" font-size = "12" style = "fill:var(--muted)" > 按地址升序,所有人一致 → 不会成环< / text >
< text x = "40" y = "290" font-size = "12.5" style = "fill:var(--ink)" > 两套顺序都不改变 case 的语义,只是决定了「先试谁」和「先锁谁」。< / text >
< / svg >
< div class = "figcap" > < b > 图 3< / b > · 同一组 case, 两套顺序: 洗牌管公平, 排序管不死锁< / div >
< / figure >
< p > < strong > 检查顺序解决公平性。< / strong > 按书写顺序试,第一个 case 会永远赢,后面的饿死;插入式洗牌让每个 case 排在第一位的概率相同。这就是规范里「伪随机均匀选择」的实现,也是同一段代码每次结果不同的原因——随机性从最早的实现就有。< / p >
< p > < strong > 加锁顺序解决死锁。< / strong > 两个 goroutine 分别写 < code > select{a, b}< / code > 和 < code > select{b, a}< / code > ,按书写顺序加锁就会互相等;按地址排成全序后,所有人以同一顺序加锁,环路不可能形成。同一把锁只加一次,遇到相同地址就跳过。< / p >
< p > 锁全部拿住之后才开始按检查顺序扫:接收 case 看有没有等待的发送方、缓冲是否非空、是否已关闭;发送 case 先看是否已关闭(直接 panic) , 再看有没有等待的接收方、缓冲是否还有空位。有就绪的就地执行并返回; 都不就绪且有 default 就走 default; 否则在每个 channel 上各挂一个等待节点,然后睡下。< / p >
< p > < span class = "tag s" > 可跳过< / span > 醒来后要重新按加锁顺序锁住全部 channel, 把自己的等待节点从其它 channel 上一个个摘掉,再统一解锁。所以 N 路 select 每次唤醒都要摘 N 次链——case 不是免费的,热路径上别写几十路 select。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box warn" >
2026-10-25 17:16:48 +08:00
< span class = "bt" > 易错点 · nil channel 在 select 里是「禁用分支」< / span >
< p > 对一个 nil 的 channel 收发会永久阻塞,但把它写进 select 的 case 里,运行时只是跳过:不报错、不就绪,等于把这个分支关掉,这是有用的技巧。危险在于同一个 nil 掉进普通收发路径——它不会报错,只会安静地卡住一个 goroutine, 等程序跑够久才被发现。< / p >
2026-10-21 14:11:30 +08:00
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > 一次 select 至少要拿 N 把锁,虽然只在有就绪分支时才真正阻塞,但锁竞争在 N 大时立刻显现;随机化还让代码不可复现,靠「它总是走这个 case」的测试迟早翻车。另外空 select 会永久 park, 而运行时只有在全部 goroutine 都睡着时才报死锁,只要还有别人在跑,它就只是泄漏。< / p >
< p class = "take" > < b > 一句话:< / b > select 是「一次检查 N 个 channel, 全不就绪才睡」; 洗牌保公平, 按地址加锁防死锁, 而 nil case 是合法的禁用开关。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-8-8" > 8.8 容量设计: 0、1、N、信号量与 worker pool< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 一条容量 0 的流水线,把某一级改成慢调用,整条链跟着一起慢——抖动会顺着会合点一路传下去。改成容量 1000, 上游立刻不再被拖, 但停机时队列里还压着上千个没跑完的任务, 内存也一直挂着。容量没变任何代码路径, 却把「慢」换了个地方出现。< / p >
< p > < span class = "tag" > 机制< / span > 容量在 make 那一刻定死,运行期不会变。它不改变收发的三条路径,只决定「发送方什么时候必须等」:容量 0 时等对方,容量 N 时等到缓冲满。< / p >
< p > < strong > 容量 0: 强同步。< / strong > 发送方必须确认对方接手才能继续,背压最及时,耦合也最紧。适合握手、阶段同步、流水线每一级的交接。代价是调度抖动直接传给上下游。< / p >
< p > < strong > 容量 1: 一个令牌或合并通知。< / strong > 只关心「有事件发生」、不需要累计每一次通知时,容量 1 加非阻塞发送天然去重:已经有一个待处理的通知就不再塞。它也能吸收一次短暂的调度抖动。< / p >
< p > < strong > 容量 N: 生产消费缓冲。< / strong > N 的含义是「系统允许的最大待处理任务数」,也是开始向上游施加背压的阈值。它不提高吞吐上限,只把排队从时间维度挪到空间维度。< / p >
< p > < strong > 信号量:容量等于并发上限。< / strong > 取令牌和还令牌各是一次收或发,容量表达的是并发度,不是队列长度。忘记释放(尤其 panic 路径没 defer) 会让令牌永久少一个, 最终整个池子卡死。< / p >
< p > < strong > worker pool: 队列容量不等于并发度。< / strong > worker 数量决定处理能力,队列容量决定允许积压多少,两者要分开调。队列过大掩盖消费不足:延迟涨、内存涨、停机还要排空;过小则生产者频繁阻塞,但背压及时。< / p >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 容量< / th > < th > 语义< / th > < th > 典型场景< / th > < th > 风险< / th > < / tr > < / thead >
< tbody >
< tr > < td > 0< / td > < td > 会合,收发必须同时就绪< / td > < td > 握手、阶段同步、严格顺序、不允许积压< / td > < td > 耦合最紧,抖动直接传导< / td > < / tr >
< tr > < td > 1< / td > < td > 一个令牌 / 合并通知< / td > < td > trigger、stop、互斥令牌、事件去重< / td > < td > 误当队列用,吞吐被串行化< / td > < / tr >
< tr > < td > N< / td > < td > 允许积压 N 个的缓冲队列< / td > < td > 生产消费、吸收突发、解耦速度差< / td > < td > 过大掩盖消费不足,延迟与内存上涨< / td > < / tr >
< tr > < td > = 并发上限< / td > < td > 信号量< / td > < td > 限制并发、保护下游< / td > < td > 漏释放令牌 → 永久卡死< / td > < / tr >
< tr > < td > jobs 队列< / td > < td > 积压容量,与 worker 数无关< / td > < td > worker pool< / td > < td > 过大导致停机排空慢、延迟高< / td > < / tr >
< / tbody >
< / table >
< / div >
2026-10-25 17:16:48 +08:00
< p > < strong > 容量怎么算。< / strong > 先按流量估:生产峰值 1000/s、消费 800/s、持续 5 秒,至少要吸收 1000 个。更通用的是「QPS 乘可接受排队时延」估上界,再用内存(容量乘元素大小)和停机排空时间收一遍。公式只对短时突发生效——长期生产大于消费时,多大容量都会被填满。< / p >
< p > 估完压测校正:看 pprof 里 goroutine 停在 < code > chan send< / code > 、< code > chan receive< / code > 的占比,用 < code > len(ch)< / code > 打点看水位。水位长期贴着容量,说明消费者不够。< / p >
2026-10-21 14:11:30 +08:00
< pre data-lang = "go" data-name = "信号量与 worker pool: 容量表达的是两件不同的事" > // 1) 信号量:容量 = 并发上限
sem := make(chan struct{}, 8)
for _, job := range jobs {
sem < - struct{}{} // 满了就阻塞,形成背压
go func(j Job) {
defer func() { < -sem }() // 必须 defer, panic 也能释放
handle(j)
}(job)
}
// 2) worker pool: 队列容量 ≠ 并发度
jobCh := make(chan Job, 200) // 缓冲:允许积压 200 个
var wg sync.WaitGroup
for i := 0; i < 8; i++ { // 并发度: 8 个 worker
wg.Add(1)
go func() {
defer wg.Done()
for j := range jobCh { // 关闭后自动退出
handle(j)
}
}()
}< / pre >
< div class = "box case" >
< span class = "bt" > 真实案例:把队列从 100 调到 10000< / span >
< p > 某服务的任务队列频繁打满,发送方阻塞导致接口超时。把容量从 100 调到 10000 后不再阻塞,
但 P99 从 80 ms 涨到 1.2 s——任务没丢, 只是排得更久。根因是消费者慢, 改成容量 200 加扩容 worker 后延迟才回落。
教训:< strong > 调大容量只是把排队从 channel 里挪到延迟里< / strong > ,不会让消费变快。< / p >
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > 无论容量多大,内存都是创建那一刻按「容量乘元素大小」付掉的;缓冲只能吸收突发,吸不住长期的产销差。队列越长,停机排空越慢、常驻内存越高,故障形态也从「阻塞」变成「延迟加内存」。< / p >
< p class = "take" > < b > 一句话:< / b > 容量决定背压发生在哪、故障长什么样: 0 是会合、1 是令牌、N 是允许积压、等于并发上限是信号量。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-8-9" > 8.9 常见模式:超时、取消、扇入扇出与泄漏< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 一个服务, goroutine 数随 QPS 线性上涨, pprof 里一大片停在 < code > chan send< / code > 。代码既没有死循环,也没有明显的泄漏点——只有一个「发完就返回」的 goroutine, 和一个先退出的消费方。这张图在超时、取消、扇出三种写法里都能重现。< / p >
< p > < span class = "tag" > 机制< / span > 这三种模式的共同点是: 阻塞点必须配一条退出路径。channel 的阻塞没有超时,唯一的出路是另一个 channel 就绪——所以要么用 select 加一条超时分支,要么用 cancel 加一条完成分支。< / p >
< p > < strong > 超时。< / strong > select 加 < code > time.After< / code > 是最常见的写法, 但要看清版本: Go 1.22 及以前, timer 在触发前不会被回收,高频路径每次都留下一个几十分钟后才释放的 timer; Go 1.23 起未停止的 timer 可被回收,坑才消失。要兼容旧版本就用 < code > time.NewTimer< / code > 加 defer 停掉。< / p >
2026-10-21 14:11:30 +08:00
< p > < strong > 取消。< / strong > 不要自己造 < code > done< / code > channel 做取消,用 < code > ctx.Done()< / code > ,
好处是超时、上游取消、请求结束能串成一条链(见 < a href = "11-context.html#sec-11-2" > 11.2< / a > )。
所有可能阻塞的发送都要配一条退出路径,这是防泄漏的基本动作:< / p >
< pre data-lang = "go" data-name = "可取消的生产者:阻塞发送必须有退出路径" > func produce(ctx context.Context, out chan< - int) error {
for i := 0; ; i++ {
select {
case out < - i:
case < -ctx.Done():
return ctx.Err()
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
// 消费方退出后, produce 会从 ctx.Done() 返回,不会永远挂在发送上
}< / pre >
2026-10-25 17:16:48 +08:00
< p > < strong > 扇出与扇入。< / strong > fan-out 是多个 worker 读同一个 channel——一个元素只会被一个 goroutine 取到, 不需要额外加锁; fan-in 是多个生产者写同一个 channel, 麻烦在关闭: 不能让每个生产者各自关, 通常用 < code > WaitGroup< / code > 加一个收尾 goroutine, 等所有人写完再关; 或者用 errgroup 收敛第一个错误并取消其余,见 < a href = "13-puzzles.html#sec-13-8" > 13.8< / a > 。< / p >
< p > < strong > done channel 广播。< / strong > 关闭一个 channel 会一次唤醒所有监听者,比往 channel 里发 N 个值简单,也不会有「谁先收到」的问题。注意广播只能做一次,需要重复通知就换新的 channel。< / p >
< p > < strong > 泄漏的模式类根因。< / strong > 接收方永久阻塞(对面不发也不关);发送方无人接收(缓冲满后永久挂起);只发不收的 goroutine( 没有退出条件) 。三者共同点是阻塞没有退出路径——第 1 章 < a href = "01-goroutine.html#sec-1-8" > 1.8< / a > 讲过起 goroutine 之前先想好怎么退出; context 那一路的泄漏(父任务取消后子任务不收手)不在这里展开,见 < a href = "11-context.html#sec-11-7" > 11.7< / a > 。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box danger" >
< span class = "bt" > 怎么确认是泄漏而不是慢< / span >
< p > 看 pprof 的 goroutine 视图:大量 G 停在 < code > chan send< / code > / < code > chan receive< / code > 且数量随 QPS
线性增长,基本就是泄漏。测试里用 < code > go.uber.org/goleak< / code > 兜底,线上用 < code > runtime.NumGoroutine()< / code >
看趋势——别只看绝对值,要看斜率。< / p >
< / div >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 代价< / span > 这些模式都有隐性开销:< code > time.After< / code > 每次调用真的建一个 timer, 延迟回收不等于免费; select 每多一条分支就多一次洗牌、多一把锁;扇出的每个 goroutine 至少 2 KB 栈。写起来最省事的模式,往往也是泄漏最多的地方。< / p >
< p class = "take" > < b > 一句话:< / b > 超时、取消、扇出是同一件事的三种写法——给阻塞点配一条退出路径;没有退出路径的 goroutine 一定会泄漏。< / p >
2026-10-21 14:11:30 +08:00
< h3 id = "sec-8-10" > 8.10 channel 与锁的取舍< / h3 >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag" > 现象< / span > 同一个计数器写两版:一版用 atomic 加一,一版交给一个专属 goroutine、每次加一都要过一次 channel。压测差三倍以上, pprof 里差别全在 < code > chan send< / code > 与 < code > chan recv< / code > 上——加法本身没变慢,慢的是为了加一次而做的两次交接。< / p >
< p > < span class = "tag" > 机制< / span > 判断标准不是「哪个快」, 而是「要表达什么」。channel 表达事件与所有权转移,天生带同步点和背压;锁表达「这段代码同一时刻只能有一个 goroutine 进来」,保护不变量,临界区要短。用 channel 保护计数器,等于用两次调度加两次拷贝换一次加法。< / p >
2026-10-21 14:11:30 +08:00
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 维度< / th > < th > channel< / th > < th > mutex / atomic< / th > < / tr > < / thead >
< tbody >
< tr > < td > 表达的语义< / td > < td > 事件、数据所有权转移、并发编排< / td > < td > 保护共享状态、短临界区< / td > < / tr >
< tr > < td > 同步点< / td > < td > 有,收发建立 happens-before< / td > < td > 有,加解锁建立< / td > < / tr >
< tr > < td > 背压< / td > < td > 天然,缓冲满即阻塞< / td > < td > 没有,要自己实现< / td > < / tr >
< tr > < td > 单次开销(量级)< / td > < td > 有缓冲约几十 ns; 无缓冲交接几百 ns< / td > < td > 约十几 ns; atomic 约几 ns< / td > < / tr >
< tr > < td > 典型误用< / td > < td > 当计数器、开无限大缓冲当队列< / td > < td > 临界区里做 I/O、锁粒度过粗< / td > < / tr >
< tr > < td > 适用< / td > < td > 流水线、worker pool、超时与取消< / td > < td > 计数器、缓存、结构体字段< / td > < / tr >
< / tbody >
< / table >
< / div >
< p > 下面是本机跑的一组 micro benchmark( Go 1.26.5, Windows, 20 逻辑核,单生产单消费、无竞争,
取三次中位数,注释是后加的):< / p >
< pre data-lang = "text" data-name = "channel 与锁的开销量级(本机实测)" > BenchmarkChanBuffered1 38.85 ns/op // ch < - i; < -ch 一次往返
BenchmarkChanUnbuffered 333.50 ns/op // 无缓冲交接,另一个 goroutine 接收
BenchmarkMutex 15.55 ns/op // Lock/Unlock 一对
BenchmarkAtomic 5.88 ns/op // atomic.Int64.Add< / pre >
2026-10-25 17:16:48 +08:00
< p > < span class = "tag s" > 可跳过< / span > 读法:容量 1 的一次「发送加接收」往返约 39 ns, 含两次 channel 操作;无缓冲交接约 330 ns, 代价主要在唤醒另一个 goroutine 并等它被调度,不在拷贝;锁 15 ns 出头, atomic 不到 6 ns。所以「channel 比锁慢」在跨 goroutine 交接时差一个数量级以上,但它买的是编排能力。< / p >
< p > 结论:传数据、做流水线、做限流和取消,用 channel; 保护 map、计数器、结构体字段, 用 < code > sync.Mutex< / code > 或 atomic( 选型表见 < a href = "10-sync.html#sec-10-10" > 10.10< / a > )。标准库也这么分:< code > context< / code > 用 channel 做取消广播,< code > sync.Map< / code > 用锁保护内部结构。< / p >
< p > < span class = "tag" > 代价< / span > 选错的代价不是一次慢几十纳秒,而是故障形状变了:拿 channel 当状态容器, 临界区被拉长到「等一次调度」, QPS 与延迟都不再可预测;反过来,拿锁去等一个事件,要么轮询要么加条件变量,本来一条 channel 能表达的编排会被摊成一堆手写状态。< / p >
< p class = "take" > < b > 一句话:< / b > 要「等一件事发生」用 channel, 要「保护一段不变量」用锁; 把 channel 当状态容器,是把几十纳秒的加法换成两次调度。< / p >
2026-10-21 14:11:30 +08:00
< div class = "box ok" >
< span class = "bt" > 面试怎么答「channel 和锁怎么选」< / span >
< p > 先说语义: channel 传所有权和事件, 适合编排与背压; mutex 保护共享状态,适合短临界区。
再说数量级: 有缓冲一次收发几十纳秒、无缓冲几百纳秒, 锁十几纳秒, atomic 几纳秒。
最后补边界:需要「等待某个事件」用 channel, 需要「保护一段不变量」用锁。< / p >
< / div >
2026-10-25 17:16:48 +08:00
< h2 id = "ch8-sum" > 全章回顾:四个判断< / h2 >
< div class = "box case" >
< span class = "bt" > 三句话把这一章收住< / span >
< p > 结构上,它是「一把锁 + 一块环形数组 + 两张等待队列」;锁只保护元数据,元素一拷完就与它无关。< / p >
< p > 语义上,容量 0 是会合、容量 N 是解耦, close 是一次广播;发送成功不等于对方处理完,关闭后读到零值也不等于出错。< / p >
< p > 工程上, channel 负责编排与背压,锁负责保护状态;每个阻塞点都要有退出路径,否则泄漏迟早会来。< / p >
< / div >
< div class = "tablewrap" >
< table >
< thead > < tr > < th > 症状< / th > < th > 先查什么< / th > < th > 回哪节< / th > < / tr > < / thead >
< tbody >
< tr > < td > goroutine 数只涨不落< / td > < td > pprof 里是否集中在 chan send 与 chan receive, 阻塞有没有退出路径< / td > < td > < a href = "#sec-8-9" > 8.9< / a > < / td > < / tr >
< tr > < td > panic: send on closed channel< / td > < td > 发送方是不是有多个、谁在做 close、读的一方有没有抢先关< / td > < td > < a href = "#sec-8-6" > 8.6< / a > < / td > < / tr >
< tr > < td > 偶发读不到数据,像是丢了< / td > < td > 是否拿值本身判结束,是否把「发送成功」当成对方收到< / td > < td > < a href = "#sec-8-4" > 8.4< / a > 、< a href = "#sec-8-6" > 8.6< / a > < / td > < / tr >
< tr > < td > 同样的代码每次走的分支不同< / td > < td > select 的随机选择,是不是在靠「总走这个 case」写逻辑< / td > < td > < a href = "#sec-8-7" > 8.7< / a > < / td > < / tr >
< tr > < td > 加了缓冲, P99 反而涨了< / td > < td > 消费能力够不够,容量是不是在掩盖消费不足< / td > < td > < a href = "#sec-8-8" > 8.8< / a > < / td > < / tr >
< tr > < td > 拿 channel 当计数器或锁用< / td > < td > 这段代码要保护的是不变量,还是等一个事件< / td > < td > < a href = "#sec-8-10" > 8.10< / a > < / td > < / tr >
< / tbody >
< / table >
< / div >
< div class = "box tip" >
< span class = "bt" > 面试怎么收尾< / span >
< p > 被问到 channel, 先给「同步点」这个定位, 再按追问往下走: 问实现就说环形缓冲加两条等待队列, 问 select 就说洗牌与按地址加锁,问容量就说背压落在哪,问取舍就说编排归 channel、状态归锁。收尾一句: 它慢的地方不在拷贝, 在调度。< / p >
< / div >
2026-10-21 14:11:30 +08:00
< / article >
< nav class = "pager" >
< a class = "prev" href = "07-map.html" > < span class = "k" > ← 上一章< / span > < span class = "v" > 第 7 章 · map: 从 hmap/bmap 到 1.24 Swiss Table< / span > < / a >
< a class = "next" href = "09-defer.html" > < span class = "k" > 下一章 →< / span > < span class = "v" > 第 9 章 · defer、panic、recover 与闭包< / span > < / a >
< / nav >
< p class = "foot" >
Go 八股 · 第 8 章 channel: CSP 的载体与并发编排< br >
< a href = "index.html" > 总目录< / a > · < a href = "../../SRE工程师/sre-learning-path/index.html" > SRE 学习路径< / a >
< / p >
< / main >
< / div >
< button id = "toTop" title = "回到顶部" > ↑< / button >
< script src = "assets/doc.js" > < / script >
< script src = "../../assets/back.js" data-portal-back = "knowledge/go" data-portal-label = "知识库 › Go 八股知识库" > < / script >
< / body >
< / html >