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

MIT 6.5840:Lecture 02 Threads and RPC

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

MIT 6.5840:Lecture 02 Threads and RPC

本篇逐行译注 MIT 6.5840 Spring 2026 Lecture 2,围绕 Go threads、并发爬虫、RPC 和失败语义,建立后续分布式实验所需的编程基础。

TL;DR

  • threads 的价值:它们可以隐藏 I/O latency、利用 multicore,并把后台任务组织成独立的执行流;代价是 shared state、coordination 和 deadlock。
  • event-driven 的替代方案:单线程显式交错多个活动,可以降低 thread cost,但失去 multicore speedup,代码也更难组织。
  • 并发爬虫的三个版本:serial、用 shared state + Mutex 协调、用 channels 协调;它们分别展示递归状态、锁保护和消息传递。
  • RPC 的抽象:client 调用远程 handler,RPC library 负责连接、marshalling、dispatch 和 reply;但远程调用永远不能等同于单机 procedure call。
  • 失败语义:客户端没有收到 reply 时,不知道请求是否到达、是否执行或只是 reply 丢失;best-effort、at-most-once 和 replicated retry 必须明确区分。

名词解释

名词含义本文对应物
GoroutineGo 对轻量执行流的称呼go func(...) { ... } 创建的并发任务
Race多个线程同时访问同一内存且至少一个写入并发更新 fetched map 或 KV map
Critical section必须受保护的共享状态操作区间Lock() 与 Unlock() 之间的代码
Channel在线程之间传值并同步的 Go 对象chan []string 传递爬虫结果
RPCRemote Procedure Callclient.Call("KV.Get", ...)
Marshalling把对象编码成 wire formatGo RPC 在网络上传输 Args 和 Reply
At-most-once同一请求最多被服务端执行一次Go RPC 不自动重发请求的基本语义

目录

章节内容
版本与来源固定 Lecture 2 及配套 Go 源文件
原文逐行翻译按 l-rpc.txt 顺序译注
并发爬虫代码原样保留 crawler.go 并说明三个实现
RPC KV 代码原样保留 kv.go 并说明请求路径
失败语义best-effort 与 at-most-once 的边界
本篇验收源文件、代码块和图片结论

版本与来源

  • 课程版本:MIT 6.5840 Spring 2026。
  • Lecture 源文件:l-rpc.txt,308 行,SHA-256:2e5edcf0c52eec3d665066193485e9a73362a236d6461af9e6dfb95445289b1e。
  • 爬虫源文件:crawler.go,183 行,SHA-256:3baffe2148ddedd02a28e80458b3c2e203070e14676129ecf44945004c274c6a。
  • KV 源文件:kv.go,124 行,SHA-256:2e6dec47c4795d9c8242f0abe233ca691863873213bbdefe1b72eb21c770f70a。
  • 翻译边界:讲义英文源行按原顺序保留,随后给出中文译文;Go 代码、函数名、变量名和 URL 原样保留。
  • 图片结论:三份纯文本源文件没有独立图片文件;原文中的 diagram 占位和 RPC ASCII 示意保留在对应位置。

原文逐行翻译

课程主题与 Go

6.5840 2026 Lecture 2: Threads and RPC

6.5840 2026 年 Lecture 2:Threads and RPC。

Topic: implementing distributed systems

主题:实现分布式系统。

... and Go programming for the labs

……以及为 labs 服务的 Go 编程。

Go threads, and the web crawler

Go threads,以及 web crawler。

Go RPC

Go RPC。

Details are Go specific but the concepts are important and widely used

具体细节与 Go 相关,但这些概念很重要,并且被广泛使用。

Why Go?

为什么选择 Go?

good support for threads

它对 threads 有良好支持。

convenient RPC

它提供了方便的 RPC。

type- and memory- safe

它具有 type safety 和 memory safety。

garbage-collected (no use after freeing problems)

它带有 garbage collector(不会出现 free 之后继续使用的问题)。

threads + GC is particularly attractive!

threads + GC 尤其有吸引力!

not too complex

它并不复杂。

Go is often used in distributed systems

Go 经常用于分布式系统。

After the tutorial, use https://golang.org/doc/effective_go.html

完成本教程后,请继续阅读 https://golang.org/doc/effective_go.html。

Threads

Threads

Threads。

a useful structuring tool, but can be tricky

它是一种有用的结构化工具,但也可能很棘手。

Go calls them goroutines; everyone else calls them threads

Go 把它们称为 goroutines;其他语言和系统通常称为 threads。

Thread = "thread of execution"

Thread = “thread of execution(执行流)”。

threads allow one program to do many things at once

threads 允许一个程序同时做许多事情。

each thread executes serially, just like a non-threaded program

每个 thread 内部仍然是 serial execution,就像一个非 threaded 程序一样。

the threads share memory

这些 threads 共享内存。

each thread includes some per-thread state:

每个 thread 都包含一些 per-thread state:

program counter, registers, stack

包括 program counter、registers 和 stack。

Why threads?

为什么使用 threads?

I/O concurrency

I/O concurrency。

Client sends requests to many servers in parallel and waits for replies.

客户端并行向多个服务器发送请求,并等待 replies。

Server processes many simultaneous client requests.

服务器处理许多同时到达的客户端请求。

  Each request may block.

每个请求都可能阻塞。

  While waiting for the disk to read data for client X,

当服务器等待磁盘为 client X 读取数据时,

    process a request from client Y.

可以处理来自 client Y 的请求。

Multicore performance

Multicore performance。

Execute code in parallel on several cores.

在多个 cores 上并行执行代码。

Convenience

Convenience。

In background, once per second, check whether each worker is still alive.

在后台每秒检查一次每个 worker 是否仍然存活。

Is there an alternative to threads?

threads 有替代方案吗?

Yes: write code that explicitly interleaves activities, in a single thread.

有:在单个 thread 中编写代码,显式地交错执行多个 activities。

Usually called "event-driven."

这通常称为“event-driven”。

Keep a table of state about each activity, e.g. each client request.

为每个 activity 保存一个 state table,例如为每个 client request 保存状态。

One "event" loop that:

使用一个“event” loop,它:

checks for new input for each activity (e.g. arrival of reply from server),

检查每个 activity 是否有新的输入(例如服务器 reply 到达),

does the next step for each activity,

为每个 activity 执行下一步,

updates state.

并更新状态。

Event-driven can get you I/O concurrency,

Event-driven 可以获得 I/O concurrency,

and eliminates thread costs (which can be substantial),

并消除 thread 的成本(这种成本可能相当高),

but doesn't get multi-core speedup,

但无法获得 multi-core speedup,

and is painful to program.

而且编程体验很痛苦。

Threading challenges

Threading challenges:

Threading challenges:

sharing data safely

安全地共享数据。

what if two threads do n = n + 1 at the same time?

如果两个 threads 同时执行 n = n + 1,会怎样?

  or one thread reads while another increments?

或者一个 thread 读取时,另一个 thread 正在递增?

this is a "race"

这就是一个“race”。

  = two threads use same memory at same time, one (or both) writes

它表示:两个 threads 同时使用同一块内存,并且其中至少一个执行写入。

  often a bug

这通常是 bug。

-> use locks (Go's sync.Mutex)

→ 使用 locks(Go 的 sync.Mutex)。

-> or avoid sharing mutable data

→ 或者避免共享 mutable data。

coordination between threads

threads 之间的 coordination。

one thread is producing data, another thread is consuming it

一个 thread 生产数据,另一个 thread 消费数据。

  how can the consumer wait (and release the CPU)?

consumer 如何等待(并释放 CPU)?

  how can the producer wake up the consumer?

producer 如何唤醒 consumer?

-> use Go channels or sync.Cond or sync.WaitGroup

→ 使用 Go channels、sync.Cond 或 sync.WaitGroup。

deadlock

deadlock。

a cycle of threads waiting for each other

一组 threads 形成了相互等待的环。

via locks, or channels, or RPC

这种环可能通过 locks、channels 或 RPC 形成。

Let's look at the tutorial's web crawler as a threading example.

下面以教程中的 web crawler 作为 threading 示例。

Web crawler

What is a web crawler?

什么是 web crawler?

goal: fetch all web pages, e.g. to feed to an indexer

目标:抓取所有网页,例如把它们提供给 indexer。

you give it a starting web page

你给它一个起始网页。

it recursively follows all links

它递归地跟随全部链接。

[diagram: pages, links, a DAG, a cycle]

[示意图:页面、链接、一个 DAG 和一个 cycle。]

but don't fetch a given page more than once

但不能多次抓取同一个页面。

and don't get stuck in cycles

也不能卡在 cycles 中。

Crawler challenges

Crawler challenges:

Exploit I/O concurrency

利用 I/O concurrency。

Network latency is more limiting than network capacity

相比 network capacity,network latency 更容易成为限制因素。

  internet latency: maybe 0.1 seconds, due to speed of light &c

internet latency 可能约为 0.1 秒,原因包括光速限制等。

  internet throughput: maybe MB/sec or GB/sec

internet throughput 可能达到每秒 MB 甚至每秒 GB 的量级。

Fetch many pages in parallel

并行抓取许多页面。

  To increase URLs fetched per second

从而提高每秒抓取的 URLs 数量。

=> Use threads for concurrency

=> 使用 threads 实现 concurrency。

Fetch each URL only once

每个 URL 只抓取一次。

avoid wasting network bandwidth

避免浪费 network bandwidth。

avoid link cycles

避免 link cycles。

be nice to remote servers

对 remote servers 友好。

=> Need to remember which URLs visited

=> 需要记住哪些 URLs 已访问过。

Know when finished

知道何时完成。

We'll look at three solutions [crawler.go on schedule page]

下面查看三种方案(schedule page 上的 crawler.go):

Serial

Serial。

Concurrent, coordination via shared data

Concurrent,通过 shared data 协调。

Concurrent, coordination via channels

Concurrent,通过 channels 协调。

Serial crawler

Serial crawler:

Serial crawler:

performs depth-first exploration via recursive Serial calls

通过递归调用 Serial 执行 depth-first exploration。

the "fetched" map avoids repeats, breaks cycles

fetched map 避免重复抓取,并打破 cycles。

a single map, passed by reference, caller sees callee's updates

它是一个按引用传递的 map,因此 caller 能看到 callee 的更新。

finished when all [recursive] links are explored: easy

当所有(递归发现的)links 都探索完时就完成:这很容易判断。

but: fetches only one page at a time -- slow

但它一次只抓取一个页面——速度很慢。

can we just put a "go" in front of the Serial() call?

我们能不能只在 Serial() 调用前加上一个 go?

what will happen?

会发生什么?

let's try it... what happened?

试试看……发生了什么?

ConcurrentMutex crawler

ConcurrentMutex crawler:

ConcurrentMutex crawler:

Creates a thread for each page fetch

为每个页面抓取创建一个 thread。

Many concurrent fetches, higher fetch rate

这样就能并发抓取许多页面,提高抓取速率。

the "go func" creates a goroutine and starts it running

go func 会创建一个 goroutine,并开始运行它。

func... is an "anonymous function"

func... 是一个“anonymous function”。

The threads share the fs.fetched map

这些 threads 共享 fs.fetched map。

So only one thread will fetch any given page

因此对于任意给定页面,最终只会有一个 thread 抓取它。

Why the Mutex (Lock() and Unlock()) in testAndSet()?

为什么 testAndSet() 中需要 Mutex(Lock() 和 Unlock())?

One reason:

一个原因是:

  Two threads make simultaneous calls to ConcurrentMutex() with same URL

两个 threads 同时使用同一个 URL 调用 ConcurrentMutex()。

    Due to two different pages containing link to same URL

这是因为两个不同页面都包含指向同一个 URL 的链接。

  T1 reads fetched[url], T2 reads fetched[url]

T1 读取 fetched[url],T2 也读取 fetched[url]。

  Both see that url hasn't been fetched (fetched[url] = false)

两者都看到该 URL 尚未被抓取(fetched[url] = false)。

  Both fetch, which is wrong

于是两者都去抓取,这是错误的。

  The mutex causes one to wait while the other does both check and set

Mutex 让一个 thread 等待,另一个 thread 同时完成检查和设置。

    So only one thread sees fetched[url]==false

这样只有一个 thread 能看到 fetched[url] == false。

  We say "the lock protects fs.fetched[]"

我们说“这个 lock 保护 fs.fetched[]”。

    But note Go does not enforce any relationship between locks and data!

但要注意,Go 不会强制检查 locks 与 data 之间的任何关系!

  The code between lock/unlock is often called a "critical section"

位于 lock/unlock 之间的代码通常称为“critical section”。

Another reason:

另一个原因是:

  Internally, map is a complex data structure (tree? expandable hash?)

map 在内部是复杂的数据结构(tree?可扩展 hash?)。

  Concurrent update/update may wreck internal invariants

并发 update/update 可能破坏其内部 invariants。

  Concurrent update/read may crash the read

并发 update/read 可能导致 read 崩溃。

defer...

defer……

What if I comment out Lock() / Unlock()?

如果把 Lock() / Unlock() 注释掉会怎样?

  go run crawler.go

运行 go run crawler.go。

    Does it always work? Always fail? Why?

它总是成功吗?总是失败吗?为什么?

  go run -race crawler.go

运行 go run -race crawler.go。

    Detects races even when output is correct!

即使输出正确,它也能检测到 races!

What if I forget to Unlock()?  deadlock

如果忘记 Unlock() 呢?会发生 deadlock。

How does the ConcurrentMutex crawler decide it is done?

ConcurrentMutex crawler 如何判断自己完成了?

sync.WaitGroup -- it's basically a counter

sync.WaitGroup——它基本上就是一个 counter。

Wait() waits for all Add()s to be balanced by Done()s

Wait() 等待所有 Add() 都由对应的 Done() 抵消。

  i.e. waits for all child threads to finish

也就是等待所有 child threads 完成。

[diagram: tree of goroutines, overlaid on cyclic URL graph]

[示意图:叠加在 cyclic URL graph 上的 goroutines tree。]

there's a WaitGroup per node in the tree

树中的每个 node 都有一个 WaitGroup。

How many concurrent threads might there be?

最多可能有多少个并发 threads?

ConcurrentChannel crawler

ConcurrentChannel crawler

ConcurrentChannel crawler。

a Go channel:

Go channel:

a channel is an object

channel 是一个对象。

  ch := make(chan int)
go
ch := make(chan int)
a channel lets one thread send an object to another thread

channel 允许一个 thread 向另一个 thread 发送对象。

ch <- x
go
ch <- x
  the sender waits until some goroutine receives

sender 会等待,直到某个 goroutine 接收它。

y := <- ch
go
y := <- ch
  a receiver waits until some goroutine sends

receiver 会等待,直到某个 goroutine 发送数据。

also: for y := range ch

还可以写成:for y := range ch。

channels both communicate and synchronize

channels 同时承担 communication 和 synchronization。

several threads can send and receive on a channel

多个 threads 可以在同一个 channel 上发送和接收。

send+recv takes less than a microsecond -- fairly cheap

send+recv 花费不到一微秒——相当便宜。

remember: sender blocks until the receiver receives!

记住:sender 会阻塞,直到 receiver 收到数据!

  "synchronous"

这就是“synchronous”。

  watch out for deadlock

要小心 deadlock。

ConcurrentChannel coordinator()

ConcurrentChannel 的 coordinator():

coordinator() creates a worker goroutine to fetch each page

coordinator() 为每个页面抓取创建一个 worker goroutine。

worker() sends slice of page's URLs on a channel

worker() 通过 channel 发送页面 URL 的 slice。

  multiple workers send on the single channel

多个 workers 在同一个 channel 上发送。

coordinator() reads URL slices from the channel

coordinator() 从 channel 读取 URL slices。

At what line does the coordinator wait?

coordinator 在哪一行等待?

Does the coordinator use CPU time while it waits?

coordinator 等待时会占用 CPU time 吗?

Note: there is no recursion here; coordinator() creates all workers.

注意:这里没有 recursion;coordinator() 创建所有 workers。

Note: no need to lock the fetched map, because it isn't shared!

注意:不需要 lock fetched map,因为它没有被共享!

How does the coordinator know it is done?

coordinator 如何知道自己完成了?

Keeps count of workers in n.

它在 n 中维护 worker 数量。

Each worker sends exactly one item on channel.

每个 worker 恰好向 channel 发送一个 item。

The channel does two things:

channel 做两件事:

1. communication of values.
  1. 传递 values。
2. notification of events (e.g. thread termination).
  1. 通知 events(例如 thread termination)。

Why is it safe for multiple threads use the same channel?

为什么多个 threads 使用同一个 channel 是安全的?

Is this a race:

下面这是 race 吗?

Worker thread modifies (creates) url slice, coordinator uses it?

Worker thread 修改(创建)URL slice,而 coordinator 使用它?

  • worker only writes slice before sending
  • worker 只在发送之前写入 slice。
  • coordinator only reads slice after receiving
  • coordinator 只在接收之后读取 slice。

So they can't use the slice at the same time, so there's no race.

因此两者不可能同时使用这个 slice,所以不存在 race。

Why does ConcurrentChannel() create a goroutine just for "ch <- ..."?

为什么 ConcurrentChannel() 专门为 ch <- ... 创建一个 goroutine?

Let's get rid of the goroutine...

把这个 goroutine 去掉试试看……

When to use sharing and locks, versus channels?

什么时候使用 sharing and locks,什么时候使用 channels?

Most (all?) problems can be solved in either style

大多数(甚至所有?)问题都可以用任一种风格解决。

What makes the most sense depends on how the programmer thinks

哪种方式最合理,取决于程序员的思考方式。

state -- sharing and locks

state——sharing and locks。

communication -- channels

communication——channels。

For the 6.824 labs, I recommend sync.Mutex/sync.Cond for shared state

对于 6.824 labs,我建议在 shared state 场景使用 sync.Mutex / sync.Cond。

Remote Procedure Call(RPC)

Remote Procedure Call (RPC)

Remote Procedure Call(RPC)。

a key piece of distributed system machinery; all the labs use RPC

这是分布式系统 machinery 的关键部分;所有 labs 都使用 RPC。

goal: easy-to-program client/server communication

目标:让 client/server communication 易于编程。

hide details of network protocols

隐藏 network protocols 的细节。

convert data (strings, arrays, maps, &c) to "wire format"

把数据(strings、arrays、maps 等)转换成“wire format”。

portability / interoperability

提供 portability / interoperability。

RPC message diagram:

RPC message diagram:

text
  Client             Server
    request--->
       <---response

客户端发送 request,服务器返回 response。

Software structure

软件结构:

text
  client app        handler fns
   stub fns         dispatcher
   RPC lib           RPC lib
     net  ------------ net

客户端 app 通过 stub fns 和 RPC lib 发出请求;服务器侧由 dispatcher 找到 handler fns;两侧 RPC lib 通过 network 连接。

Go example: kv.go on schedule page

Go 示例:schedule page 上的 kv.go。

A toy key/value storage server -- Put(key,value), Get(key)->value

一个 toy key/value storage server——Put(key,value)、Get(key)->value。

Uses Go's RPC library

它使用 Go 的 RPC library。

Common:

共同约定:

Declare Args and Reply struct for each server handler.

为每个 server handler 声明 Args 和 Reply struct。

Client:

Client:

connect()'s Dial() creates a TCP connection to the server

connect() 中的 Dial() 创建到 server 的 TCP connection。

get() and put() are client "stubs"

get() 和 put() 是 client “stubs”。

Call() asks the RPC library to perform the call

Call() 要求 RPC library 执行调用。

  you specify connection, function name, arguments, place to put reply

调用者需要指定 connection、function name、arguments 以及放置 reply 的位置。

  library marshalls args, sends request, waits, unmarshalls reply

library 会 marshall args、发送 request、等待,并 unmarshall reply。

  return value from Call() indicates whether it got a reply

Call() 的返回值表示是否收到了 reply。

  usually you'll also have a reply.Err indicating service-level failure

通常还会有一个 reply.Err,表示 service-level failure。

Server:

Server:

Go requires server to declare an object with methods as RPC handlers

Go 要求 server 声明一个对象,并把它的方法作为 RPC handlers。

Server then registers that object with the RPC library

Server 随后把这个对象注册给 RPC library。

Server accepts TCP connections, gives them to RPC library

Server 接受 TCP connections,并把它们交给 RPC library。

The RPC library

RPC library 会:

  reads each request

读取每个 request。

  creates a new goroutine for this request

为这个 request 创建一个新的 goroutine。

  unmarshalls request

unmarshall request。

  looks up the named object (in table create by Register())

查找命名对象(在 Register() 创建的 table 中)。

  calls the object's named method (dispatch)

调用该对象的命名方法(dispatch)。

  marshalls reply

marshall reply。

  writes reply on TCP connection

把 reply 写入 TCP connection。

The server's Get() and Put() handlers

server 的 Get() 和 Put() handlers:

  Must lock, since RPC library creates a new goroutine for each request

必须加锁,因为 RPC library 会为每个 request 创建新的 goroutine。

  read args; modify reply

它们读取 args,并修改 reply。

RPC 细节与失败

A few details:

一些细节:

Binding: how does client know what server computer to talk to?

Binding:client 如何知道应该和哪台 server computer 通信?

For Go's RPC, server name/port is an argument to Dial

对于 Go RPC,server name/port 是 Dial 的参数。

Big systems have some kind of name or configuration server

大型系统会有某种 name server 或 configuration server。

Marshalling: format data into packets

Marshalling:把数据格式化成 packets。

Go's RPC library can pass strings, arrays, objects, maps, &c

Go 的 RPC library 可以传递 strings、arrays、objects、maps 等。

Go passes pointers by copying the pointed-to data

Go 通过复制指针指向的数据来传递 pointers。

Cannot pass channels or functions

不能传递 channels 或 functions。

Marshals only exported fields (i.e., fields w/ CAPITAL letter)

它只 marshall exported fields(也就是以大写字母开头的 fields)。

RPC problem: what to do about failures?

RPC 问题:如何处理 failures?

e.g. lost packet, broken network, slow server, crashed server

例如 packet 丢失、network 损坏、server 缓慢或 server 崩溃。

What does a failure look like to the client RPC library?

对于 client RPC library 来说,failure 看起来是什么样?

Client never sees a response from the server

Client 永远没有看到 server 的 response。

Client does not know if the server saw the request!

Client 不知道 server 是否看到了 request!

[diagram of losses at various points]

[示意图:不同位置发生丢失的情况。]

Maybe server never saw the request

可能 server 从未看到 request。

Maybe server executed, crashed just before sending reply

可能 server 已经执行,但在发送 reply 前崩溃。

Maybe server executed, but network died just before delivering reply

也可能 server 已经执行,但 network 在交付 reply 前断开。

Remote procedure call doesn't behave the same as procedure call on a single machine!

Remote procedure call 的行为不会和单机上的 procedure call 相同!

A recurring challenge in implementing distributed systems

这是实现分布式系统时反复出现的挑战。

Simplest failure-handling scheme: "best-effort RPC"

最简单的 failure-handling scheme:“best-effort RPC”。

Call() waits for response for a while

Call() 等待一段时间以获取 response。

If none arrives, re-send the request

如果没有 response 到达,就重新发送 request。

Do this a few times

这样重复几次。

Then give up and return an error

之后放弃并返回 error。

Q: is "best effort" easy for applications to cope with?

问题:应用程序是否容易处理“best effort”?

重发与 at-most-once

A particularly bad situation:

有一种特别糟糕的情况:

client executes

client 执行:

go
Put("k", 10)
Put("k", 20)

both succeed

两次都成功。

what will Get("k") yield?

那么 Get("k") 会得到什么?

[diagram, timeout, re-send, original arrives late]

[示意图:timeout、重发,以及原始请求迟到。]

Q: is best effort ever OK?

问题:best effort 有没有适用的场景?

read-only operations

只读操作。

operations that it's harmless to repeat

重复执行不会造成伤害的操作。

 e.g. DB checks if record has already been inserted

例如,数据库会检查记录是否已经插入。

Other common semantics: at-most-once

另一种常见语义:at-most-once。

For example, Go RPC is a simple form of "at-most-once"

例如,Go RPC 是一种简单的“at-most-once”形式。

open TCP connection

打开 TCP connection。

write request to TCP connection

把 request 写入 TCP connection。

Go RPC never re-sends a request

Go RPC 永远不会重新发送 request。

  So server won't see duplicate requests

因此 server 不会看到 duplicate requests。

Go RPC code returns an error if it doesn't get a reply

如果没有收到 reply,Go RPC code 会返回 error。

  perhaps after a timeout (from TCP)

可能是在 timeout 之后(timeout 来自 TCP)。

  perhaps server didn't see request

可能 server 没有看到 request。

  perhaps server processed request but server/net failed before reply came back

也可能 server 已经处理 request,但 server 或 network 在 reply 返回之前失败。

Labs explore others way of implementing at-most-once

Labs 会探索实现 at-most-once 的其他方式。

No retry is too restrictive for replicated servers

对 replicated servers 来说,完全不 retry 的限制太严格。

Like to retry at another replica if first replica fails

如果第一个 replica 失败,通常希望在另一个 replica 上 retry。

并发爬虫代码

下面完整保留官方 crawler.go。源码中的三种实现分别对应 Serial、ConcurrentMutex 和 ConcurrentChannel;本篇正文只翻译讲义,代码本身保持可复制运行的 Go 原文。

go
package main

import (
	"fmt"
	"sync"
)

//
// Several solutions to the crawler exercise from the Go tutorial
// https://tour.golang.org/concurrency/10
//

//
// Serial crawler
//

func Serial(url string, fetcher Fetcher, fetched map[string]bool) {
	if fetched[url] {
		return
	}
	fetched[url] = true
	urls, err := fetcher.Fetch(url)
	if err != nil {
		return
	}
	for _, u := range urls {
		Serial(u, fetcher, fetched)
	}
}

//
// Concurrent crawler with shared state and Mutex
//

type fetchState struct {
	mu      sync.Mutex
	fetched map[string]bool
}

func (fs *fetchState) testAndSet(url string) bool {
	fs.mu.Lock()
	defer fs.mu.Unlock()
	r := fs.fetched[url]
	fs.fetched[url] = true
	return r
}

func ConcurrentMutex(url string, fetcher Fetcher, fs *fetchState) {
	if fs.testAndSet(url) {
		return
	}
	urls, err := fetcher.Fetch(url)
	if err != nil {
		return
	}
	var done sync.WaitGroup
	for _, u := range urls {
		done.Add(1)
		go func(u string) {
			ConcurrentMutex(u, fetcher, fs)
			done.Done()
		}(u)
	}
	done.Wait()
}

func makeState() *fetchState {
	return &fetchState{fetched: make(map[string]bool)}
}

//
// Concurrent crawler with channels
//

func worker(url string, ch chan []string, fetcher Fetcher) {
	urls, err := fetcher.Fetch(url)
	if err != nil {
		ch <- []string{}
	} else {
		ch <- urls
	}
}

func coordinator(ch chan []string, fetcher Fetcher) {
	n := 1
	fetched := make(map[string]bool)
	for urls := range ch {
		for _, u := range urls {
			if fetched[u] == false {
				fetched[u] = true
				n += 1
				go worker(u, ch, fetcher)
			}
		}
		n -= 1
		if n == 0 {
			break
		}
	}
}

func ConcurrentChannel(url string, fetcher Fetcher) {
	ch := make(chan []string)
	go func() {
		ch <- []string{url}
	}()
	coordinator(ch, fetcher)
}

//
// main
//

func main() {
	fmt.Printf("=== Serial===\n")
	Serial("http://golang.org/", fetcher, make(map[string]bool))

	fmt.Printf("=== ConcurrentMutex ===\n")
	ConcurrentMutex("http://golang.org/", fetcher, makeState())

	fmt.Printf("=== ConcurrentChannel ===\n")
	ConcurrentChannel("http://golang.org/", fetcher)
}

//
// Fetcher
//

type Fetcher interface {
	// Fetch returns a slice of URLs found on the page.
	Fetch(url string) (urls []string, err error)
}

// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult

type fakeResult struct {
	body string
	urls []string
}

func (f fakeFetcher) Fetch(url string) ([]string, error) {
	if res, ok := f[url]; ok {
		fmt.Printf("found:   %s\n", url)
		return res.urls, nil
	}
	fmt.Printf("missing: %s\n", url)
	return nil, fmt.Errorf("not found: %s", url)
}

// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
	"http://golang.org/": &fakeResult{
		"The Go Programming Language",
		[]string{
			"http://golang.org/pkg/",
			"http://golang.org/cmd/",
		},
	},
	"http://golang.org/pkg/": &fakeResult{
		"Packages",
		[]string{
			"http://golang.org/",
			"http://golang.org/cmd/",
			"http://golang.org/pkg/fmt/",
			"http://golang.org/pkg/os/",
		},
	},
	"http://golang.org/pkg/fmt/": &fakeResult{
		"Package fmt",
		[]string{
			"http://golang.org/",
			"http://golang.org/pkg/",
		},
	},
	"http://golang.org/pkg/os/": &fakeResult{
		"Package os",
		[]string{
			"http://golang.org/",
			"http://golang.org/pkg/",
		},
	},
}

三个实现的核心差异是:Serial 把状态放在调用栈和一个 map 中;ConcurrentMutex 共享 fetched 并用 Mutex 保护 test-and-set;ConcurrentChannel 不共享 fetched,由 coordinator 通过 channel 接收 worker 的结果并负责调度。

RPC KV 代码

下面完整保留官方 kv.go。它把一个 toy KV server 暴露成 KV.Get 和 KV.Put 两个 RPC handlers;RPC library 会为每个 request 创建 goroutine,因此 handler 必须保护共享的 kv.data。

go
package main

import (
	"fmt"
	"log"
	"net"
	"net/rpc"
	"sync"
)

//
// Common RPC request/reply definitions
//

type PutArgs struct {
	Key   string
	Value string
}

type PutReply struct {
}

type GetArgs struct {
	Key string
}

type GetReply struct {
	Value string
}

//
// Client
//

func connect() *rpc.Client {
	client, err := rpc.Dial("tcp", ":1234")
	if err != nil {
		log.Fatal("dialing:", err)
	}
	return client
}

func get(key string) string {
	client := connect()
	args := GetArgs{ key }
	reply := GetReply{}
	err := client.Call("KV.Get", &args, &reply)
	if err != nil {
		log.Fatal("error:", err)
	}
	client.Close()
	return reply.Value
}

func put(key string, val string) {
	client := connect()
	args := PutArgs{ key, val }
	reply := PutReply{}
	err := client.Call("KV.Put", &args, &reply)
	if err != nil {
		log.Fatal("error:", err)
	}
	client.Close()
}

//
// Server
//

type KV struct {
	mu   sync.Mutex
	data map[string]string
}

func server() {
	kv := &KV{data: map[string]string{}}
	rpcs := rpc.NewServer()
	rpcs.Register(kv)
	l, e := net.Listen("tcp", ":1234")
	if e != nil {
		log.Fatal("listen error:", e)
	}
	go func() {
		for {
			conn, err := l.Accept()
			if err == nil {
				go rpcs.ServeConn(conn)
			} else {
				break
			}
		}
		l.Close()
	}()
}

func (kv *KV) Get(args *GetArgs, reply *GetReply) error {
	kv.mu.Lock()
	defer kv.mu.Unlock()

	reply.Value = kv.data[args.Key]

	return nil
}

func (kv *KV) Put(args *PutArgs, reply *PutReply) error {
	kv.mu.Lock()
	defer kv.mu.Unlock()

	kv.data[args.Key] = args.Value

	return nil
}

//
// main
//

func main() {
	server()

	put("subject", "6.5840")
	fmt.Printf("Put(subject, 6.5840) done\n")
	fmt.Printf("get(subject) -> %s\n", get("subject"))
}

请求路径是:client stub 调用 client.Call → RPC library marshall Args → TCP connection → server RPC library 创建 goroutine → dispatch 到 KV.Get / KV.Put → marshall Reply → client unmarshall。这里的 sync.Mutex 保护的是 server 内存中的 map,不是 RPC 本身的可靠性。

失败语义

Lecture 2 的关键边界不是“如何发出 RPC”,而是“没有收到 reply 时无法知道发生了什么”。一次请求可能在以下任意位置失败:发送前、网络传输中、server 执行前、server 执行后但 reply 发送前,或 reply 返回途中。因此:

方案是否重发服务端可能执行次数适用边界
Best-effort RPC超时后重发若干次0 次、1 次或多次只适合 read-only 或重复无害的操作
Go RPC 基本语义不自动重发至多一次,但客户端可能不知道是否执行失败时返回 error,不能直接推出请求未执行
Replicated retry可能向其他 replica 重试必须额外设计去重或 request ID后续容错服务需要处理

Put("k", 10) 超时后重发 Put("k", 20) 的场景说明:即使客户端观察到第二次成功,也不能仅凭 response 顺序推断服务端最终状态;请求的实际到达和执行顺序必须由服务端语义定义。后续 Lab 4 会通过 Raft log、client ID 和 request ID,把这种不确定性变成可验证的 replicated-state-machine 行为。

本篇验收

  • 已固定 l-rpc.txt 308 行、crawler.go 183 行和 kv.go 124 行,并记录各自 SHA-256。
  • Lecture 英文源行按原顺序译注;crawler.go 与 kv.go 完整原样保留。
  • 原文中的 web crawler diagram、RPC message diagram、failure diagram 均保留文字占位或 ASCII 示意;三份源文件没有独立 raster image。
  • 本篇是 Spring 2026 lecture track 的第 2 篇;下一篇为 Lecture 3《GFS》。

参考资料

← 返回列表
← 上一篇 MIT 6.5840:Lecture 01 Introduction 下一篇 → MIT 6.5840:Lecture 03 GFS

评论 (0)

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