目录
正在加载目录…
正在阅读专栏 分布式共识系统专栏 第 14 篇 · 共 59 篇 · 24%

MIT 6.5840:Lecture 05 Go Patterns

发布于 2026-09-21 10:05 · 最后编辑于 2026-09-21 18:14 · 版本 v2 · 字数 12,746 · 预计阅读 26 分钟 👁 23 次阅读

本篇按 MIT 6.5840 Spring 2026 guest lecture 的 PDF 页面和源文本顺序翻译 Russ Cox 的 Go concurrency patterns;代码、状态机示意、stack trace 和课堂提示保留在对应位置。

MIT 6.5840:Lecture 05 Go Patterns

TL;DR

  • Concurrency 不等于 parallelism:前者是组织独立执行过程,后者是同时执行计算。
  • 本讲的主线:把“数据状态”逐步改写成“代码状态”,再用 goroutines 和 channels 表达状态机、发布/订阅、任务调度等并发结构。
  • 核心提醒:goroutine 不会自动结束;必须明确谁负责关闭 channel、终止循环和回收 goroutine。
  • 工程工具:pprof 用于观察 live goroutine stacks,-race 用于检测 data race;两者都应在开发乃至生产中使用。

版本与来源

  • 课程版本:MIT 6.5840 Spring 2026。
  • 官方 PDF:Patterns and Hints for Concurrency in Go,Russ Cox,73 页。
  • 本地源文件 SHA-256:a8764e0ed6400ec2f912a499ce3f74c60e4bd0fac084960cbcbf1aa7eedcefd2。
  • 课程日程:MIT 6.5840 Spring 2026 Schedule。
  • 翻译边界:PDF 中的自然语言按页面和文本顺序翻译;Go 代码、正则表达式、stack trace、命令和地址原样保留。后续页面会继续追加到本篇。
  • 图件结论:PDF 没有独立 raster image 对象;页面中的箭头、提示框和代码布局属于 slide 的矢量/文本排版。当前笔记保留这些内容的源文本位置,必要时用代码块表达原始布局。

目录

章节说明
逐页翻译:1–19第 1–19 页:concurrency、状态机、goroutine 与 pprof
逐页翻译:20–25第 20–25 页:Publish/subscribe server 的接口与 mutex 版本
逐页翻译:26–73第 26–73 页:待续写入本篇

逐页翻译:1–19

第 1 页:标题

Patterns and Hints

Patterns 和 Hints(模式与提示)。

for Concurrency in Go

面向 Go concurrency。

Russ Cox

Russ Cox。

MIT 6.5840 / “Spring” 2026

MIT 6.5840 / “Spring” 2026。

第 2 页:Concurrency 不等于 Parallelism

Concurrency is not Parallelism

Concurrency 不是 Parallelism。

Concurrency: composition of independently executing processes.

Concurrency:独立执行过程的组合。

Parallelism: simultaneous execution of (possibly related)

Parallelism:同时执行(可能相互关联的)

computations.

computations。

Concurrency is about dealing with lots of things at once.

Concurrency 关注的是同时处理很多事情。

Parallelism is about doing lots of things at once.

Parallelism 关注的是同时做很多事情。

第 3 页:Prologue

Prologue:

序章:

Goroutines for State

用 Goroutines 表达 State。

第 4 页:目标正则表达式

/"([^"\]|\.)*"/

text
/"([^"\\]|\\.)*"/

这个正则表达式匹配一个双引号包围的字符串,并允许用反斜杠表示 escape sequence。

第 5 页:显式状态机

页面中的 Go 代码原样保留:

go
state := 0
for {
    c := read()
    switch state {
    case 0:
        if c != '"' {
            return false
        }
        state = 1
    case 1:
        if c == '"' {
            return true
        }
        if c == '\\' {
            state = 2
        } else {
            state = 1
        }
    case 2:
        state = 1
    }
}

这里把解析过程编码为显式的 data state:0 表示尚未进入字符串,1 表示正在字符串中,2 表示刚读到 escape 字符。

第 6 页:从数据状态中抽出读取动作

页面展示了两个保持相同语义、但重新安排 read() 调用位置的版本。代码原样保留:

go
state := 0
for {
    c := read()
    switch state {
    case 0:

        if c != '"' {
            return false
        }
        state = 1
    case 1:

        if c == '"' {
            return true
        }
        if c == '\\' {
            state = 2
        } else {
            state = 1
        }
    case 2:

        state = 1
    }
}
state := 0
for {

    switch state {
    case 0:
        c := read()
        if c != '"' {
            return false
        }
        state = 1
    case 1:
        c := read()
        if c == '"' {
            return true
        }
        if c == '\\' {
            state = 2
        } else {
            state = 1
        }
    case 2:
        read()
        state = 1
    }
}

关键变化是:把“下一步需要读取什么”逐渐放进每个 state 的代码中,为后续把 state 变成独立执行流做准备。

第 7 页:进一步拆分状态代码

前半部分继续使用 switch state,后半部分则把每个状态写成可以跳转到的代码标签。原始代码保留:

go
state := 0
for {

    switch state {
    case 0:
        c := read()
        if c != '"' {
            return false
        }
        state = 1
    case 1:
        c := read()
        if c == '"' {
            return true
        }
        if c == '\\' {
            state = 2
        } else {
            state = 1
        }
    case 2:
        read()
        state = 1
    }
}

state0:
    c := read()
    if c != '"' {
        return false
    }
    goto state1
state1:
    c := read()
    if c == '"' {
        return true
    }
    if c == '\\' {
        goto state2
    } else {
        goto state1
    }
state2:
    read()
    goto state1

这一步把状态转移直接变成程序控制流。

第 8 页:去掉显式状态变量

第二个版本不再需要 state 变量,而是使用代码位置本身表示当前状态:

go
state0:
    c := read()
    if c != '"' {
        return false
    }
    goto state1
state1:
    c := read()
    if c == '"' {
        return true
    }
    if c == '\\' {
        goto state2
    } else {
        goto state1
    }
state2:
    read()
    goto state1

state0:
    c := read()
    if c != '"' {
        return false
    }

state1:
    c := read()
    if c == '"' {
        return true
    }
    if c == '\\' {
        goto state2
    } else {
        goto state1
    }
state2:
    read()
    goto state1

代码的布局开始反映状态机的结构,而不是把所有状态重新编码为一个整数。

第 9 页:把 escape 处理内联

页面展示两个等价版本:第一个保留 state2,第二个在遇到反斜杠时直接读取下一个字符:

go
state0:
    c := read()
    if c != '"' {
        return false
    }

state1:
    c := read()
    if c == '"' {
        return true
    }
    if c == '\\' {
        goto state2
    } else {
        goto state1
    }
state2:
    read()
    goto state1

state0:
    c := read()
    if c != '"' {
        return false
    }

state1:
    c := read()
    if c == '"' {
        return true
    }
    if c == '\\' {
        read()
        goto state1
    } else {
        goto state1
    }

这里的意图是消除不必要的 data state,而不是改变解析规则。

第 10 页:合并循环结构

页面继续把 escape 分支内联到循环中:

go
state0:
    c := read()
    if c != '"' {
        return false
    }

state1:
    c := read()
    if c == '"' {
        return true
    }
    if c == '\\' {
        read()
    }
    goto state1

state0:
    c := read()
    if c != '"' {
        return false
    }

state1:
    c := read()
    if c == '"' {
        return true
    }
    if c == '\\' {
        read()
        goto state1
    } else {
        goto state1
    }

第 11 页:只保留必要的状态

在进一步简化后,解析主体可以写成:

go
state0:
    c := read()
    if c != '"' {
        return false
    }

state1:
    c := read()
    if c == '"' {
        return true
    }
    if c == '\\' {
        read()
    }
    goto state1

c := read()
if c != '"' {
    return false
}

for {
    c := read()
    if c == '"' {
        return true
    }
    if c == '\\' {
        read()
    }
}

状态机的控制流已经接近普通的解析循环。

第 12 页:普通循环版本

页面给出进一步整理后的代码:

go
c := read()
if c != '"' {
    return false
}

for {
    c := read()
    if c == '"' {
        return true
    }
    if c == '\\' {
        read()
    }
}

if read() != '"' {
    return false
}

var c rune
for c != '"' {
    c = read()
    if c == '\\' {
        read()
    }
}
return true

第 13 页:inEscape 状态

第二种写法用布尔变量表示是否正在 escape:

go
if read() != '"' {
    return false
}
inEscape := false
for {
    c := read()
    if inEscape {
        inEscape = false
        continue
    }
    if c == '"' {
        return true
    }
    if c == '\\' {
        inEscape = true
    }
}

页面下半部分再次给出上一页的 var c rune 版本,作为对照。这里的重点不是某一种写法,而是观察 data state 如何逐步转化为代码结构。

第 14 页:把状态转成函数

页面给出封装后的解析函数:

go
func parse(read func() rune) bool {
    if read() != '"' {
        return false
    }

    var c rune
    for c != '"' {
        c = read()
        if c == '\\' {
            read()
        }
    }
    return true
}

state==0 →

state==0 →

state==1 →

state==1 →

state==2 →

state==2 →

Hint: Convert data state into code state

提示:当这样做能让程序更清晰时,把 data state 转换为 code state。

when it makes programs clearer.

当它能够让程序更清晰时。

← inEscape==false

← inEscape==false。

← inEscape==true

← inEscape==true。

第 15 页:用结构体保存状态

页面代码原样保留:

go
type quoter struct {
    state int
}

func (q *quoter) Init() {
    r.state = 0
}

func (q *quoter) Write(c rune) Status {
    switch q.state {
    case 0:
        if c != '"' {
            return BadInput
        }
        q.state = 1
    case 1:
        if c == '"' {
            return Success
        }
        if c == '\\' {
            q.state = 2
        } else {
            q.state = 1
        }
    case 2:
        q.state = 1
    }
    return NeedMoreInput
}

这里把 parser 变成持有 state 的对象:每次 Write 输入一个 rune,并返回 BadInput、Success 或 NeedMoreInput。

第 16 页:用 goroutine 持有代码状态

页面给出用 channel 和 goroutine 重构的版本:

go
type quoter struct {
    char   chan rune
    status chan Status
}

func (q *quoter) Init() {
    q.char = make(chan rune)
    q.status = make(chan Status)
    go q.parse()
    <-q.status // always NeedMoreInput
}

func (q *quoter) Write(c rune) Status {
    q.char <- c
    return <-q.status
}

func (q *quoteReader) parse() {
    if q.read() != '"' {
        q.status <- SyntaxError
        return
    }

    var c rune
    for c != '"' {
        c = q.read()
        if c == '\\' {
            q.read()
        }
    }
    q.status <- Done
}

func (q *quoter) read() int {
    q.status <- NeedMoreInput
    return <-q.char
}

Hint: Use additional goroutines

提示:使用额外的 goroutines

to hold additional code state.

来持有额外的 code state。

相比把 state 存成整数,这种写法让“状态”存在 goroutine 当前停留的代码位置中;channel 负责把输入和状态结果连接起来。

第 17 页:观察 goroutine 生命周期

页面中的 Go 程序原样保留:

go
package main

import (
    "net/http"
    _ "net/http/pprof"
)

var c = make(chan int)

func main() {
    for i := range 100 {
        go f(0x10*i)
    }
    http.ListenAndServe("localhost:8080", nil)
}

func f(x int) {
    g(x+1)
}

func g(x int) {
    h(x+1)
}

func h(x int) {
    c <- 1
    f(x+1)
}

Hint: Know why and when

提示:要知道每个 goroutine

each goroutine will exit.

为什么、何时会退出。

程序启动 100 个 goroutines,但 h 会阻塞在向没有 receiver 的 channel c 发送数据上;因此它们不会自然结束。这是 goroutine leak/liveness 问题的最小示例。

第 18 页:用 SIGQUIT 查看 stack

命令和输出原样保留:

text
$ go run x.go
^\\

SIGQUIT: quit
PC=0x105a17b m=0 sigcode=0

...

goroutine 18 [chan send]:
main.h(0x12)
    /tmp/x.go:26 +0x45
main.g(0x11)
    /tmp/x.go:22 +0x20
main.f(0x10)
    /tmp/x.go:18 +0x20
created by main.main
    /tmp/x.go:12 +0x42

goroutine 19 [chan send]:
main.h(0x22)
    /tmp/x.go:26 +0x45
main.g(0x21)
    /tmp/x.go:22 +0x20
main.f(0x20)
    /tmp/x.go:18 +0x20
created by main.main
    /tmp/x.go:12 +0x42

...

Hint: Type Ctrl-\ to kill a program and

提示:输入 Ctrl-\ 终止程序,

dump all its goroutine stacks.

并 dump 所有 goroutines 的 stacks。

第 19 页:goroutine profile

pprof 输出原样保留:

text
goroutine profile: total 106
100 @ 0x12d8715 0x12d86c0 0x12d8690 0x1058d61
#   0x12d8714   main.h+0x44 /tmp/x.go:26
#   0x12d86bf   main.g+0x1f /tmp/x.go:22
#   0x12d868f   main.f+0x1f /tmp/x.go:18

2 @ 0x11ddfcf 0x11dddcf 0x1248265 0x124f513 0x1253636 0x1058d61
#   0x11ddfce   net/textproto.(*Reader).readLineSlice+0x5e  go/src/net/textproto/reader.go:55
#   0x11dddce   net/textproto.(*Reader).ReadLine+0x2e       go/src/net/textproto/reader.go:36
#   0x1248264   net/http.readRequest+0xa4                   go/src/net/http/request.go:926
#   0x124f512   net/http.(*conn).readRequest+0x1b2          go/src/net/http/server.go:934
#   0x1253635   net/http.(*conn).serve+0x495                go/src/net/http/server.go:1763

1 @ 0x115a102 0x116b1cd 0x124dc92 0x1058d61
#   0x115a101   net.(*netFD).Read+0x51                      go/src/net/fd_unix.go:207
#   0x116b1cc   net.(*conn).Read+0x6c                       go/src/net/net.go:182
#   0x124dc91   net/http.(*connReader).backgroundRead+0x61  go/src/net/http/server.go:656

1 @ 0x12cfe22 0x12cfc20 0x12cc6e5 0x12d8051 0x12d8365 0x1254b84 0x1255fa0 0x1257312 0x1253845
0x1058d61
#   0x12cfe21   runtime/pprof.writeRuntimeProfile+0xa1      go/src/runtime/pprof/pprof.go:634
#   0x12cfc1f   runtime/pprof.writeGoroutine+0x9f           go/src/runtime/pprof/pprof.go:596
#   0x12cc6e4   runtime/pprof.(*Profile).WriteTo+0x3b4      go/src/runtime/pprof/pprof.go:310
#   0x12d8050   net/http/pprof.handler.ServeHTTP+0x1d0      go/src/net/http/pprof/pprof.go:232
#   0x12d8364   net/http/pprof.Index+0x1e4                  go/src/net/http/pprof/pprof.go:244
#   0x1254b83   net/http.HandlerFunc.ServeHTTP+0x43         go/src/net/http/server.go:1942
#   0x1255f9f   net/http.(*Server).Serve+0x12f              go/src/net/http/server.go:2242
#   0x1257311   net/http.serverHandler.ServeHTTP+0x91       go/src/net/http/server.go:2572
#   0x1253844   net/http.(*conn).serve+0x6a4                go/src/net/http/server.go:1825

Hint: Use the HTTP server’s

提示:使用 HTTP server 的

/debug/pprof/goroutine

/debug/pprof/goroutine

to inspect live goroutine stacks.

来检查 live goroutine stacks。

逐页翻译:20–25

第 20 页:Pattern #1

Pattern #1

模式 #1。

Publish/subscribe server

Publish/subscribe server(发布/订阅服务器)。

第 21 页:PubSub 接口

接口代码原样保留:

go
type PubSub interface {
    // Publish publishes the event e to
    // all current subscriptions.
    Publish(e Event)

    // Subscribe registers c to receive future events.
    // All subscribers receive events in the same order,
    // and that order respects program order:
    // if Publish(e1) happens before Publish(e2),
    // subscribers receive e1 before e2.
    Subscribe(c chan<- Event)

    // Cancel cancels the prior subscription of channel c.
    // After any pending already-published events
    // have been sent on c, the server will signal that the
    // subscription is cancelled by closing c.
    Cancel(c chan<- Event)
}

接口的语义是:Publish 发送给当前所有订阅者;所有订阅者看到相同的事件顺序,并且这个顺序遵守 program order;Cancel 要等已经发布且待发送的事件发完,再通过关闭 channel 表示订阅结束。

第 22 页:关闭 channel 表示结束

接口代码再次原样保留:

go
type PubSub interface {
    // Publish publishes the event e to
    // all current subscriptions.
    Publish(e Event)

    // Subscribe registers c to receive future events.
    // All subscribers receive events in the same order,
    // and that order respects program order:
    // if Publish(e1) happens before Publish(e2),
    // subscribers receive e1 before e2.
    Subscribe(c chan<- Event)

    // Cancel cancels the prior subscription of channel c.
    // After any pending already-published events
    // have been sent on c, the server will signal that the
    // subscription is cancelled by closing c.
    Cancel(c chan<- Event)
}

Hint: Close a channel to signal

提示:关闭 channel,用来表示

that no more values will be sent.

不会再发送更多 values。

第 23 页:带 Mutex 的初始实现

页面中的实现原样保留:

go
type Server struct {
    mu sync.Mutex
    sub map[chan<- Event]bool
}

func (s *Server) Init() {
    s.sub = make(map[chan<- Event]bool)
}

func (s *Server) Publish(e Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    for c := range s.sub {
        c <- e
    }
}

func (s *Server) Subscribe(c chan<- Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    if s.sub[c] {
        panic("pubsub: already subscribed")
    }
    s.sub[c] = true
}

func (s *Server) Cancel(c chan<- Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    if !s.sub[c] {
        panic("pubsub: not subscribed")
    }
    close(c)
    delete(s.sub, c)
}

这个版本用 mu 保护 sub map,但 Publish 在持有 mutex 时向每个 subscriber 发送。如果某个 subscriber 没有及时接收,整个服务器会阻塞,其他订阅、取消和发布也会被拖住。

第 24 页:使用 defer 解锁

页面再次展示相同实现,并突出以下提示:

go
type Server struct {
    mu sync.Mutex
    sub map[chan<- Event]bool
}

func (s *Server) Init() {
    s.sub = make(map[chan<- Event]bool)
}

func (s *Server) Publish(e Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    for c := range s.sub {
        c <- e
    }
}

func (s *Server) Subscribe(c chan<- Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    if s.sub[c] {
        panic("pubsub: already subscribed")
    }
    s.sub[c] = true
}

func (s *Server) Cancel(c chan<- Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    if !s.sub[c] {
        panic("pubsub: not subscribed")
    }
    close(c)
    delete(s.sub, c)
}

Hint: Prefer defer for unlocking mutexes.

提示:解锁 mutex 时,优先使用 defer。

这样即使函数中途 return 或 panic,也不容易遗漏 unlock;不过 defer 只能保证解锁,不能解决 Publish 在锁内阻塞的结构性问题。

第 25 页:实现的阻塞边界

页面继续展示同一个 Mutex 版本的代码:

go
type Server struct {
    mu sync.Mutex
    sub map[chan<- Event]bool
}

func (s *Server) Init() {
    s.sub = make(map[chan<- Event]bool)
}

func (s *Server) Publish(e Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    for c := range s.sub {
        c <- e
    }
}

func (s *Server) Subscribe(c chan<- Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    if s.sub[c] {
        panic("pubsub: already subscribed")
    }
    s.sub[c] = true
}

func (s *Server) Cancel(c chan<- Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    if !s.sub[c] {
        panic("pubsub: not subscribed")
    }
    close(c)
    delete(s.sub, c)
}

Hint: Consider the effect

提示:考虑 slow goroutines 的影响。

这一页在代码演示中继续强调:锁的生命周期、channel 的关闭时机和发送操作之间必须有明确的所有权关系。后续页面会把共享状态改为由一个 goroutine 独占,用 channel 消息进行协调。

逐页翻译:26–73

第 26 页:处理 slow goroutines 的选项

Options for slow goroutines

处理 slow goroutines 的选项。

•Slow down event generation.

• 降低 event generation 的速度。

•Drop events.

• 丢弃 events。

Examples: os/signal, runtime/pprof

例子:os/signal、runtime/pprof。

•Queue an arbitrary number of events.

• 对任意数量的 events 排队。

Hint: Think carefully before

提示:在引入

introducing unbounded queuing.

unbounded queuing 之前要仔细思考。

慢 receiver 会反过来影响 producer、内存占用和系统的 liveness;选择降速、丢弃还是排队,取决于事件是否可丢失以及系统是否有明确的容量边界。

第 27 页:把状态交给 goroutine

页面先保留原来的 Mutex 数据结构,然后给出 channel-owned server 的结构:

go
type Server struct {
    mu sync.Mutex
    sub map[chan<- Event]bool
}

func (s *Server) Init() {
    s.sub = make(map[chan<- Event]bool)
}

type Server struct {
    publish   chan Event
    subscribe chan subReq
    cancel    chan subReq
}

type subReq struct {
    c  chan<- Event
    ok chan bool
}

func (s *Server) Init() {
    s.publish = make(chan Event)
    s.subscribe = make(chan subReq)
    s.cancel = make(chan subReq)
    go s.loop()
}

后一个 Server 不再保存 mu 和 sub map;它把操作发送给 loop goroutine,由这个 goroutine 独占 subscription state。

第 28 页:server loop

页面同时展示 Mutex 版本和新的 loop 实现;核心代码原样保留:

go
func (s *Server) Publish(e Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    for c := range s.sub {
        c <- e
    }
}

func (s *Server) Subscribe(c chan<- Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    if s.sub[c] {
        panic("pubsub: already subscribed")
    }
    s.sub[c] = true
}

func (s *Server) Cancel(c chan<- Event) {
    s.mu.Lock()
    defer s.mu.Unlock()

    if !s.sub[c] {
        panic("pubsub: not subscribed")
    }
    close(c)
    delete(s.sub, c)
}

func (s *Server) loop() {
    sub := make(map[chan<- Event]bool)
    for {
        select {
        case e := <-s.publish:
            for c := range sub {
                c <- e
            }

        case r := <-s.subscribe:
            if sub[r.c] {
                r.ok <- false
                break
            }
            sub[r.c] = true
            r.ok <- true

        case c := <-s.cancel:
            if !sub[r.c] {
                r.ok <- false
                break
            }
            close(r.c)
            delete(sub, r.c)
            r.ok <- true
        }
    }
}

select 把 publish、subscribe、cancel 三类请求汇聚到一个拥有 sub map 的执行流中,避免多个 goroutines 直接并发修改共享 map。

第 29 页:把公共方法接到请求 channel

页面先重复旧的 Mutex 方法,随后给出新的公共方法:

go
func (s *Server) Publish(e Event) {
    s.publish <- e
}

func (s *Server) Subscribe(c chan<- Event) {
    r := subReq{c: c, ok: make(chan bool)}
    s.subscribe <- r
    if !<-r.ok {
        panic("pubsub: already subscribed")
    }
}

func (s *Server) Cancel(c chan<- Event) {
    r := subReq{c: c, ok: make(chan bool)}
    s.cancel <- r
    if !<-r.ok {
        panic("pubsub: not subscribed")
    }
}

公共方法通过 request channel 把工作交给 loop,并通过 ok channel 返回成功或失败。这样调用方仍然获得同步的 API,但共享状态只有一个 owner。

第 30 页:完整的 goroutine-owned server

完整实现原样保留:

go
type Server struct {
    publish chan Event
    subscribe chan subReq
    cancel chan subReq
}

type subReq struct {
    c chan<- Event
    ok chan bool
}

func (s *Server) Init() {
    s.publish = make(chan Event)
    s.subscribe = make(chan subReq)
    s.cancel = make(chan subReq)
    go s.loop()
}

func (s *Server) Publish(e Event) {
    s.publish <- e
}

func (s *Server) Subscribe(c chan<- Event) {
    r := subReq{c: c, ok: make(chan bool)}
    s.subscribe <- r
    if !<-r.ok {
        panic("pubsub: already subscribed")
    }
}

func (s *Server) Cancel(c chan<- Event) {
    r := subReq{c: c, ok: make(chan bool)}
    s.cancel <- r
    if !<-r.ok {
        panic("pubsub: not subscribed")
    }
}
func (s *Server) loop() {
    sub := make(map[chan<- Event]bool)
    for {
        select {
        case e := <-s.publish:
            for c := range sub {
                c <- e
            }

        case r := <-s.subscribe:
            if sub[r.c] {
                r.ok <- false
                break
            }
            sub[r.c] = true
            r.ok <- true

        case c := <-s.cancel:
            if !sub[r.c] {
                r.ok <- false
                break
            }
            close(r.c)
            delete(sub, r.c)
            r.ok <- true
        }
    }
}

Hint: Convert mutexes

提示:当这样做能够让程序更清晰时,

into goroutines

把 mutexes 转换成 goroutines,

when it makes programs clearer

如果这能让程序更清晰。

第 31 页:为慢 receiver 建立队列

go
func helper(in <-chan Event,
            out chan<- Event) {
    var q []Event
    for {
        select {
        case e := <-in:
            q = append(q, e)
        case out <- q[0]:
            q = q[1:]
        }
    }
}

helper 在输入和输出之间维护一个 event queue:输入可继续接收,输出则按队列头部发送。实际使用时还要处理空队列,否则 q[0] 会越界。

第 32 页:让空队列禁用输出分支

页面先重复第 31 页版本,然后给出通过 nil channel 禁用 select case 的版本:

go
func helper(in <-chan Event,
            out chan<- Event) {
    var q []Event
    for {
        // Decide whether and what to send.
        var sendOut chan<- Event
        var next Event
        if len(q) > 0 {
            sendOut = out
            next = q[0]
        }

        select {
        case e := <-in:
            q = append(q, e)
        case sendOut <- next:
            q = q[1:]
        }
    }
}

Decide whether and what to send.

决定是否发送,以及发送什么。

当 q 为空时,sendOut 为 nil;向 nil channel 的 send case 永远不会被 select 选中,于是只会接收新 event。

第 33 页:正确关闭 helper

页面先重复上一版本,然后给出能够结束的版本:

go
func helper(in <-chan Event,
            out chan<- Event) {
    var q []Event
    for in != nil || len(q) > 0 {
        // Decide whether and what to send.
        var sendOut chan<- Event
        var next Event
        if len(q) > 0 {
            sendOut = out
            next = q[0]
        }

        select {
        case e, ok := <-in:
            if !ok {
                in = nil // stop receiving from in
                break
            }
            q = append(q, e)
        case sendOut <- next:
            q = q[1:]
        }
    }
    close(out)
}

当 in 被关闭时,把 in 设为 nil,停止接收;但仍然把队列中已有的 events 发完,最后关闭 out。这同时处理了输入结束和缓冲事件排空两个生命周期问题。

第 34 页:原始 loop 的 slow subscriber 问题

loop 的原始版本再次保留:

go
func (s *Server) loop() {
    sub := make(map[chan<- Event]bool)
    for {
        select {
        case e := <-s.publish:
            for c := range sub {
                c <- e
            }

        case r := <-s.subscribe:
            if sub[r.c] {
                r.ok <- false
                break
            }
            sub[r.c] = true
            r.ok <- true

        case c := <-s.cancel:
            if !sub[r.c] {
                r.ok <- false
                break
            }
            close(r.c)
            delete(sub, r.c)
            r.ok <- true
        }
    }
}

如果某个 c <- e 阻塞,整个 loop 就无法处理其他 subscribers 或新的请求。问题不是 map 的互斥,而是一个慢 receiver 被放在了所有事件的关键路径上。

第 35 页:每个 subscriber 独立运行

页面保留原始 loop,并给出为每个 subscriber 建立 helper 的版本:

go
func (s *Server) loop() {
    sub := make(map[chan<- Event]chan<- Event)
    for {
        select {
        case e := <-s.publish:
            for _, h := range sub {
                h <- e
            }

        case r := <-s.subscribe:
            if sub[r.c] != nil {
                r.ok <- false
                break
            }
            h = make(chan Event)
            go helper(h, r.c)
            sub[r.c] = h
            r.ok <- true

        case c := <-s.cancel:
            if sub[r.c] == nil {
                r.ok <- false
                break
            }
            close(sub[r.c])
            delete(sub, r.c)
            r.ok <- true
        }
    }
}

Hint: Use goroutines

提示:使用 goroutines,

to let independent concerns

让彼此独立的 concerns

run independently.

独立运行。

这里每个订阅者拥有自己的 queueing helper;server loop 只需把 event 发送给 helper,不必直接等待最终 receiver。

第 36 页:Pattern #2

Pattern #2

模式 #2。

Work scheduler

Work scheduler(工作调度器)。

第 37 页:调度器接口

func Schedule(servers []string, numTask int,

go
func Schedule(servers []string, numTask int,
              call func(srv string, task int))

Schedule 接收服务器列表、任务数量和实际执行单个任务的 callback。

第 38 页:把空闲服务器放进 buffered channel

go
func Schedule(servers []string, numTask int,
              call func(srv string, task int)) {

    idle := make(chan string, len(servers))
    for _, srv := range servers {
        idle <- srv
    }
}

Hint: Use a buffered channel

提示:使用 buffered channel

as a concurrent blocking queue.

作为 concurrent blocking queue。

idle 中的每个字符串代表一个可用 server;从 channel 接收就是借用一个 server,执行完后再把它放回去。

第 39 页:为每个任务启动 goroutine

go
func Schedule(servers []string, numTask int,
              call func(srv string, task int)) {

    idle := make(chan string, len(servers))
    for _, srv := range servers {
        idle <- srv
    }

    for task := range numTask {
        go func() {
            srv := <-idle
            call(srv, task)
            idle <- srv
        }()
    }
}

Hint: Use goroutines

提示:使用 goroutines,

to let independent concerns

让彼此独立的 concerns

run independently.

独立运行。

这个版本允许调用方快速创建任意数量的 goroutines;但它没有等待任务完成,也没有限制同时存在的任务 goroutines 数量。

第 40 页:警惕无界排队

页面重复上一版本的实现:

go
func Schedule(servers []string, numTask int,
              call func(srv string, task int)) {

    idle := make(chan string, len(servers))
    for _, srv := range servers {
        idle <- srv
    }

    for task := range numTask {
        go func() {
            srv := <-idle
            call(srv, task)
            idle <- srv
        }()
    }
}

Hint: Think carefully before

提示:在引入

introducing unbounded queuing.

unbounded queuing 之前要仔细思考。

当 numTask 很大时,任务会先变成大量阻塞的 goroutines;这把队列压力从 channel 转移到了 goroutine 和 runtime,而不是消除了压力。

第 41 页:由主循环领取 server

页面给出另一种把 server 放在外层领取的版本:

go
func Schedule(servers []string, numTask int,
              call func(srv string, task int)) {

    idle := make(chan string, len(servers))
    for _, srv := range servers {
        idle <- srv
    }

    for task := range numTask {
        srv := <-idle
        go func() {
            call(srv, task)
            idle <- srv
        }()
    }
}

这里领取 server 的动作发生在主循环,因此主循环会在没有空闲 server 时阻塞;但仍然要注意闭包捕获的 task 和 srv 的语义,以及任务完成后的等待协议。

第 42 页:等待所有 server 归还

go
func Schedule(servers []string, numTask int,
              call func(srv string, task int)) {

    idle := make(chan string, len(servers))
    for _, srv := range servers {
        idle <- srv
    }

    for task := range numTask {
        srv := <-idle
        go func() {
            call(srv, task)
            idle <- srv
        }()
    }

    for range servers {
        <-idle
    }
}

最后从 idle 接收 len(servers) 次,等待所有 server 都回到 channel。这种方法把“server 已归还”同时作为资源回收和完成信号。

第 43 页:调度器的完整等待形式

页面继续展示相同实现:

go
func Schedule(servers []string, numTask int,
              call func(srv string, task int)) {

    idle := make(chan string, len(servers))
    for _, srv := range servers {
        idle <- srv
    }

    for task := range numTask {
        srv := <-idle
        go func() {
            call(srv, task)
            idle <- srv
        }()
    }

    for range servers {
        <-idle
    }
}

关键不在于“启动 goroutine”,而在于定义清楚 scheduler 何时返回,以及 callback 抛出 panic、永久阻塞或任务失败时系统如何处理。

第 44 页:固定数量的 worker goroutines

go
func Schedule(servers []string, numTask int,
              call func(srv string, task int)) {

    work := make(chan int)
    done := 0

    runTasks := func(srv string) {
        for task := range work {
            call(srv, task)
        }
        done++
    }

    for _, srv := range servers {
        go runTasks(srv)
    }

    for task := range numTask {
        work <- task
    }
    close(work)

    for done < len(servers) {
        runtime.Gosched()
    }
}

Hint: Think carefully before

提示:在引入

introducing unbounded queuing.

unbounded queuing 之前要仔细思考。

Hint: Close a channel to signal

提示:关闭 channel,用来表示

that no more values will be sent.

不会再发送更多 values。

这个版本让每台 server 对应一个长期存在的 worker;work 不需要缓存所有任务,worker 会在任务流上同步消费。但 done++ 本身是并发写入,下一页会用 race detector 暴露它。

第 45 页:race detector

页面中的代码和 race 输出原样保留:

text
$ go run -race /tmp/x.go
==================
WARNING: DATA RACE
Write at 0x00c0000121d8 by goroutine 6:
  main.Schedule.func1()
      /tmp/x.go:19 +0x80
  main.Schedule.gowrap1()
      /tmp/x.go:23 +0x48

Previous read at 0x00c0000121d8 by main goroutine:
  main.Schedule()
      /tmp/x.go:31 +0x27c
  main.main()
      /tmp/x.go:6 +0x90

Goroutine 6 (running) created at:
  main.Schedule()
      /tmp/x.go:23 +0x13c
  main.main()
      /tmp/x.go:6 +0x90
==================

Hint: Use the race detector,

提示:使用 race detector,

for development and even production.

用于 development,甚至 production。

done 的递增和主 goroutine 的读取没有同步,因此是 data race。-race 不是只用于课堂演示的工具;它能把这种通常难以稳定复现的并发错误定位到访问栈。

第 46 页:多个 worker 同时更新 done

页面继续展示 scheduler 代码和另一份 race 输出:

text
$ go run -race /tmp/x.go
==================
WARNING: DATA RACE
Write at 0x00c00019c008 by goroutine 7:
  main.Schedule.func1()
      /tmp/x.go:19 +0x80
  main.Schedule.gowrap1()
      /tmp/x.go:23 +0x48

Previous write at 0x00c00019c008 by goroutine 6:
  main.Schedule.func1()
      /tmp/x.go:19 +0x80
  main.Schedule.gowrap1()
      /tmp/x.go:23 +0x48

Goroutine 7 (running) created at:
  main.Schedule()
      /tmp/x.go:23 +0x13c
  main.main()
      /tmp/x.go:6 +0x90

Goroutine 6 (finished) created at:
  main.Schedule()
      /tmp/x.go:23 +0x13c
  main.main()
      /tmp/x.go:6 +0x90
==================

这个 race 是两个 worker 同时写 done,不是主 goroutine 读取造成的。用普通变量表示完成计数时,必须加同步;也可以让完成事件通过 channel 传递。

第 47 页:通过 channel 共享完成事件

Hint:

提示:

Don’t communicate by sharing memory.

不要通过共享内存来通信。

Share memory by communicating.

通过通信来共享内存。

页面给出把 done 改为 channel 的版本:

go
work := make(chan int)
done := make(chan bool)

runTasks := func(srv string) {
    for task := range work {
        call(srv, task)
    }
    done <- true
}

...

for range servers {
    <-done
}

worker 不再递增共享整数,而是在退出时发送一个完成事件;调度器接收与 server 数量相同的事件即可判断所有 worker 已结束。

第 48 页:完整的完成 channel 版本

go
func Schedule(servers []string, numTask int,
              call func(srv string, task int)) {

    work := make(chan int)
    done := make(chan bool)

    runTasks := func(srv string) {
        for task := range work {
            call(srv, task)
        }
        done <- true
    }

    for _, srv := range servers {
        go runTasks(srv)
    }

    for task := range numTask {
        work <- task
    }
    close(work)

    for range servers {
        <-done
    }
}

Hint: Use goroutines

提示:使用 goroutines,

to let independent concerns

让彼此独立的 concerns

run independently.

独立运行。

第 49 页:动态 server 与完成事件

页面把 server 集合视为 channel,并展示按 task 发送完成事件的重构方向:

go
runTasks := func(srv string) {
   for task := range work {
        call(srv, task)
        done <- true
    }
}

...

for task := range numTask {
    work <- task
}

for range numTask {
    <-done
}

如果完成信号按 task 发送,就要等待 task 数量的 signals;如果按 worker 退出发送,就要等待 worker 数量的 signals。两者表达的是不同的生命周期。

第 50 页:错误的通信顺序与 deadlock

页面中的关键输出原样保留:

text
Hint: Know why and when
each communication will proceed.
$ go run /tmp/x.go
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.Schedule(0xc4200120c0, 0x3, 0x3, 0x14, 0x106acc8)
 /tmp/x.go:26 +0x150
main.main()
 /tmp/x.go:4 +0x96

goroutine 5 [chan send]:
main.Schedule.func1(0x1066bc0, 0x1)
 /tmp/x.go:15 +0xba
created by main.Schedule.func2
 /tmp/x.go:21 +0x5f

Hint: Know why and when

提示:要知道每次 communication

each communication will proceed.

何时会继续执行。

主 goroutine 在发送下一个 task 时等待 receiver,而 worker 在发送 done 时又等待 receiver;如果没有并行地安排两类通信,就会形成环形等待。

第 51 页:用 select 同时处理 work 和 done

页面展示两种改进方向:

go
i := 0
WorkLoop:
    for task := range numTask {
        for {
            select {
            case work <- task:
                continue WorkLoop
            case <-done:
                i++
            }
        }
    }
    close(work)

    for ; i < numTask; i++ {
        <-done
    }

select 允许调度器在 work 可以发送时推进任务,在 done 到达时先消费完成事件,从而避免发送端和完成端互相等待。

第 52 页:用 goroutine 隔离任务生产者

页面给出把 task 生产放入独立 goroutine 的片段:

go
go func() {
    for task := range numTask {
        work <- task
    }
    close(work)
}()

Hint: Use goroutines

提示:使用 goroutines,

to let independent concerns

让彼此独立的 concerns

run independently.

独立运行。

这样主 goroutine 可以专注于接收完成事件;生产者负责在所有 task 发送完后关闭 work。

第 53 页:有界 buffered work queue

页面将 work channel 改为:

go
work := make(chan int, numTask)

Hint: Think carefully before

提示:在引入

introducing unbounded queuing.

unbounded queuing 之前要仔细思考。

如果 numTask 本身是明确且可接受的上限,这种 buffer 可以简化生产者和 worker 的协调;如果任务量无界,就不能把无界增长简单伪装成巨大 buffer。

第 54 页:buffered scheduler

go
func Schedule(servers chan string, numTask int,
              call func(srv string, task int)) {

    work := make(chan int, numTask)
    done := make(chan bool)

    runTasks := func(srv string) {
        for task := range work {
            call(srv, task)
            done <- true
        }
    }

    go func() {
        for _, srv := range servers {
            go runTasks(srv)
        }
    }()

    for task := range numTask {
        work <- task
    }
    close(work)

    for range numTask {
        <-done
    }
}

有界 buffer 让生产者可以先放入有限数量的 tasks,但完成协议仍然必须明确:此处每个 task 对应一个 done event。

第 55 页:失败任务重新入队

页面把 callback 改成返回 bool,并展示失败后重新发送 task 的片段:

go
runTasks := func(srv string) {
    for task := range work {
        if call(srv, task) {
           done <- true
        } else {
           work <- task
        }
    }
}

...

for task := range numTask {
    work <- task
}

for range numTask {
    <-done
}
close(work)

Hint: Know why and when

提示:要知道每次 communication

each communication will proceed.

何时会继续执行。

失败 task 重新写入 work,因此需要确保 buffer、worker 数量和关闭时机不会形成新的阻塞或过早结束。

第 56 页:关闭 work 的时机

Hint: Close a channel to signal

提示:关闭 channel,用来表示

that no more values will be sent.

不会再发送更多 values。

如果 worker 仍可能把失败 task 放回 work,就不能在所有初始 task 发送完后立即关闭 channel;必须等所有 task 成功完成,再关闭输入 channel。

第 57 页:成功才发送 done

go
func Schedule(servers chan string, numTask int,
              call func(srv string, task int) bool) {

    work := make(chan int, numTask)
    done := make(chan bool)

    runTasks := func(srv string) {
        for task := range work {
            if call(srv, task) {
                done <- true
            } else {
                work <- task
            }
        }
    }

    go func() {
        for _, srv := range servers {
            go runTasks(srv)
        }
    }()

    for task := range numTask {
        work <- task
    }

    for range numTask {
        <-done
    }
    close(work)
}

这里只有成功的 callback 才会产生一个 done event;失败任务重新回到 work queue。等到收到 numTask 个成功事件后,再关闭 work。

第 58 页:动态 server 与退出

页面给出更完整的退出控制:

go
work := make(chan int, numTask)
done := make(chan bool)
exit := make(chan bool)

...

go func() {
    for {
        select {
        case srv := <-servers:
            go runTasks(srv)
        case <-exit:
            return
        }
    }
}()

...

for range numTask {
    <-done
}
close(work)
exit <- true

Hint: Make sure you know

提示:务必知道

why and when each goroutine will exit.

每个 goroutine 为什么、何时会退出。

动态 server 生产者、worker、任务队列和退出信号必须形成完整的生命周期闭环;否则即使任务已经完成,也可能留下永久等待的 goroutine。

第 59 页:Pattern #3

Pattern #3

模式 #3。

Replicated service client

Replicated service client(复制服务客户端)。

第 60 页:复制服务客户端接口

接口代码原样保留:

go
type ReplicatedClient interface {
    // Init initializes the client to use the given servers.
    // To make a particular request later,
    // the client can use callOne(srv, args), where srv
    // is one of the servers from the list.
    Init(servers []string, callOne func(string, Args) Reply)

    // Call makes a request on any available server.
    // Multiple goroutines may call Call concurrently.
    Call(args Args) Reply
}

Call 必须从可用的 replicas 中选择 server;多个 goroutines 可以并发调用同一个 client。

第 61 页:保存 server 列表和偏好

go
type Client struct {
    servers []string
    callOne func(string, Args) Reply

    mu     sync.Mutex
    prefer int
}

func (c *Client) Init(servers []string, callOne func(string, Args) Reply) {
    c.servers = servers
    c.callOne = callOne
}

Hint: Use a mutex if that is

提示:如果 mutex 是

the clearest way to write the code.

写出清晰代码的方式,就使用 mutex。

prefer 用于记住最近成功的 server;这类小型共享状态不必为了追求全 channel 化而强行改写,清晰的 mutex 可能更合适。

第 62 页:先向一个 replica 发起请求

go
func (c *Client) Call(args Args) Reply {
    type result struct {
        serverID int
        reply Reply
    }

    done := make(chan result, 1)
    id := ...

    go func() {
        done <- result{id, c.callOne(c.servers[id], args)}
    }()
}

Hint: Use goroutines

提示:使用 goroutines,

to let independent concerns

让彼此独立的 concerns

run independently.

独立运行。

request goroutine 可以阻塞在网络调用上,而 Call 自己负责 timeout、重试或切换 server。

第 63 页:timeout 与 goroutine 生命周期

go
func (c *Client) Call(args Args) Reply {
    type result struct {
        serverID int
        reply Reply
    }

    const timeout = 1 * time.Second
    t := time.NewTimer(timeout)
    defer t.Stop()

    done := make(chan result, 1)

    id := ...

    go func() {
        done <- result{id, c.callOne(c.servers[id], args)}
    }()

    select {
    case r := <-done:
        return r.reply
    case <-t.C:
        // timeout
    }
}

Hint: Stop timers you don’t need.

提示:停止不再需要的 timers。

(fixed in Go 1.23)

(Go 1.23 已修复相关问题。)

Hint: Know why and when

提示:要知道每个 goroutine

each goroutine will exit.

为什么、何时会退出。

Hint: Know why and when

提示:要知道每次 communication

each communication will proceed.

何时会继续执行。

timeout 返回后,底层 callOne goroutine 可能仍在运行;done 使用容量为 1 的 buffer,允许它最终报告结果而不因无人接收而永久阻塞,但这不等于取消了实际 RPC。

第 64 页:依次尝试 replicas

go
func (c *Client) Call(args Args) Reply {
    type result struct {
        serverID int
        reply Reply
    }

    const timeout = 1 * time.Second
    t := time.NewTimer(timeout)
    defer t.Stop()

    done := make(chan result, len(c.servers))

    for id := range c.servers {
        go func() {
            done <- result{id, c.callOne(c.servers[id], args)}
        }()

        select {
        case r := <-done:
            return r.reply
        case <-t.C:
            // timeout
            t.Reset(timeout)
        }
    }

    r := <-done
    return r.reply
}

每次 timeout 后尝试下一个 server。done 的容量至少要能容纳可能仍在返回的 request goroutines,否则超时后的迟到结果可能重新造成阻塞。

第 65 页:记录最近成功的 server

go
c.mu.Lock()
    prefer := c.prefer
c.mu.Unlock()

var r result
for off := range c.servers {
    id := (prefer + off) % len(c.servers)
    go func() {
        done <- result{id, c.callOne(c.servers[id], args)}
    }()

    select {
    case r = <-done:
        goto Done
    case <-t.C:
        // timeout
        t.Reset(timeout)
    }
}

r = <-done
Done:
    c.mu.Lock()
    c.prefer = r.serverID
    c.mu.Unlock()
    return r.reply

Hint: Use a goto if that is

提示:如果 goto 是

the clearest way to write the code.

写出清晰代码的方式,就使用 goto。

这里 goto Done 直接跳过重复的收尾逻辑;判断标准仍然是代码是否清晰,而不是把某个语言特性当作绝对禁忌。

第 66 页:Pattern #4

Pattern #4

模式 #4。

Protocol multiplexer

Protocol multiplexer(协议多路复用器)。

第 67 页:多路复用接口

接口代码原样保留:

go
type ProtocolMux interface {
    // Init initializes the mux to manage messages to the given service.
    Init(Service)

    // Call makes a request with the given message and returns the reply.
    // Multiple goroutines may call Call concurrently.
    Call(Msg) Msg
}

type Service interface {
    // ReadTag returns the muxing identifier in the request or reply message.
    // Multiple goroutines may call ReadTag concurrently.
    ReadTag(Msg) int64

    // Send sends a request message to the remote service.
    // Send must not be called concurrently with itself.
    Send(Msg)

    // Recv waits for and returns a reply message from the remote service.
    // Recv must not be called concurrently with itself.
    Recv() Msg
}

Service 的 Send 和 Recv 各自不能并发调用,而 ProtocolMux.Call 必须支持并发调用;因此需要把串行的 service 操作与并发的 client-facing API 解耦。

第 68 页:Mux 状态

go
type Mux struct {
    srv  Service
    send chan Msg

    mu sync.Mutex
    pending map[int64]chan<- Msg
}

func (m *Mux) Init(srv Service) {
    m.srv = srv
    m.pending = make(map[int64]chan Msg)
    go m.sendLoop()
    go m.recvLoop()
}

pending 按 tag 把请求映射到等待该 reply 的 channel。一个 send loop 串行调用 srv.Send,一个 recv loop 串行调用 srv.Recv。

第 69 页:send loop

go
func (m *Mux) sendLoop() {
    for args := range m.send {
        m.srv.Send(args)
    }
}

send loop 从 m.send 读取消息,并保证对底层 Service.Send 的调用是串行的。

第 70 页:recv loop 与 reply 分发

go
func (m *Mux) recvLoop() {
    for {
        reply := m.srv.Recv()
        tag := m.srv.ReadTag(reply)

        m.mu.Lock()
        done := m.pending[tag]
        delete(m.pending, tag)
        m.mu.Unlock()

        if done == nil {
            panic("unexpected reply")
        }
        done <- reply
    }
}

recv loop 收到 reply 后读取 tag,在 pending 中找到对应 waiter,删除映射,再把 reply 发送给等待者。未知 tag 表示协议状态错误,因此直接 panic。

第 71 页:并发 Call

页面先展示 Tag 与 ReadTag 的命名变体,随后给出完整 Call:

go
func (m *Mux) Call(args Msg) (reply Msg) {
    tag := m.srv.ReadTag(args)
    done := make(chan Msg, 1)

    m.mu.Lock()
    if m.pending[tag] != nil {
        m.mu.Unlock()
        panic("mux: duplicate call tag")
    }
    m.pending[tag] = done
    m.mu.Unlock()

    m.send <- args
    return <-done
}

Hint: Use goroutines, channels,

提示:如果这样最清晰,就把 goroutines、channels

and mutexes together if that is

和 mutexes 一起使用,

the clearest way to write the code.

来写出清晰的代码。

这个例子没有把某一种同步原语绝对化:goroutines 负责独立执行,channels 负责串行化底层 I/O,mutex 保护 pending map。

第 72 页:Hints

Hints

Hints(提示)。

第 73 页:总结提示

Use the race detector, for development and even production.

使用 race detector,用于 development,甚至 production。

Don’t communicate by sharing memory. Share memory by communicating.

不要通过共享内存来通信;通过通信来共享内存。

Convert data state into code state when it makes programs clearer.

当这样做能让程序更清晰时,把 data state 转换为 code state。

Convert mutexes into goroutines when it makes programs clearer.

当这样做能让程序更清晰时,把 mutexes 转换为 goroutines。

Use additional goroutines to hold additional code state.

使用额外的 goroutines 持有额外的 code state。

Use goroutines to let independent concerns run independently.

使用 goroutines,让彼此独立的 concerns 独立运行。

Consider the effect of slow goroutines.

考虑 slow goroutines 的影响。

Know why and when each communication will proceed.

要知道每次 communication 为什么、何时会继续执行。

Know why and when each goroutine will exit.

要知道每个 goroutine 为什么、何时会退出。

Type Ctrl-\\ to kill a program and dump all its goroutine stacks.

输入 Ctrl-\\ 终止程序,并 dump 所有 goroutines 的 stacks。

Use the HTTP server’s /debug/pprof/goroutine to inspect live goroutine stacks.

使用 HTTP server 的 /debug/pprof/goroutine 检查 live goroutine stacks。

Use a buffered channel as a concurrent blocking queue.

把 buffered channel 用作 concurrent blocking queue。

Think carefully before introducing unbounded queuing.

在引入 unbounded queuing 之前要仔细思考。

Close a channel to signal that no more values will be sent.

关闭 channel,用来表示不会再发送更多 values。

Use a mutex if that is the clearest way to write the code.

如果 mutex 是写出清晰代码的方式,就使用 mutex。

Prefer defer for unlocking mutexes.

解锁 mutex 时优先使用 defer。

Use a goto if that is the clearest way to write the code.

如果 goto 是写出清晰代码的方式,就使用 goto。

Use goroutines, channels, and mutexes together

把 goroutines、channels 和 mutexes 一起使用,

if that is the clearest way to write the code.

如果这样能写出最清晰的代码。

当前进度

  • 已完成并核对第 1–73 页的页面顺序、文字和代码位置。
  • Lecture 5 PDF 的所有页面均已写入;代码、race output、stack trace、提示框和协议接口均已保留。
  • 已完成本篇全目录 checker/lint、页序审计和代码 fence 检查;下一篇为 Lecture 6《Raft (1)》。

参考资料

← 返回列表
← 上一篇 MIT 6.5840:Lecture 04 Fault-Tolerant Agreement and Paxos 下一篇 → MIT 6.5840:Lecture 06 RSM and Raft (1)

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论