介绍

Go 的并发原语使得构建有助于高效使用I/O和多核CPU的流数据管道变得更容易。
这篇文档给出了这种管道的例子,重点介绍了操作失败时出现的细微差别,并介绍了干净处理错误的技术。

Go’s concurrency primitives make it easy to construct streaming data pipelines that make efficient use of I/O and multiple CPUs. This article presents examples of such pipelines, highlights subtleties that arise when operations fail, and introduces techniques for dealing with failures cleanly.

什么是 pipeline (流水线)

在 Go 中并未对其进行正式定义;它只是许多种并行程序中的一种。但,非正式地,管道是通过 channel 链接起来的一系列的 Stage (阶段),其中每个 stage 是一组运行相同函数的的 goroutines 。在每个 Stage 中的goroutines 行为如下:

  • 通过输入 (inbound) channel 接受从上游 (upstrem) 发来的值
  • 在那些值上执行一些函数,通常会产生新的值
  • 通过输出 (outbound) channel 给下游 (downstream) 发送值

    There’s no formal definition of a pipeline in Go; it’s just one of many kinds of concurrent programs. Informally, a pipeline is a series of stages connected by channels, where each stage is a group of goroutines running the same function. In each stage, the goroutines

    • receive values from upstream via inbound channels
    • perform some function on that data, usually producing new values
    • send values downstream via outbound channels

除了第一个和最后一个 stage 各有一个输入 channel 和 输出 channel 外,其他每个 stage 可以有任意数量的输入和输出channel。第一个 stage 有时也称为源 (source) 或生产者 (producer) ;最后一个 stage 可称为 sink (槽 ?) 或 消费者 (consumer)。
我们将从一个简单的 pipeline 例子开始解释这个 idea 和技术。 稍后我们将给出更多现实例子。

Each stage has any number of inbound and outbound channels, except the first and last stages, which have only outbound or inbound channels, respectively. The first stage is sometimes called the source or producer; the last stage, the sink or consumer. We’ll begin with a simple example pipeline to explain the ideas and techniques. Later, we’ll present a more realistic example.

平方数

想想一个有三个 stage 的 pipeline。
第一个 stage ,gen是一个将整数列表转换为用于发出列表中整数的通道的函数。
gen 函数启动一个发送 channel 中整数并在所有值被发送后关闭 channel 的 goroutine

Consider a pipeline with three stages. The first stage, gen, is a function that converts a list of integers to a channel that emits the integers in the list. The gen function starts a goroutine that sends the integers on the channel and closes the channel when all the values have been sent:

  1. func gen(nums ...int) <-chan int {
  2. out := make(chan int)
  3. go func() {
  4. for _, n := range nums {
  5. out <- n
  6. }
  7. close(out)
  8. }()
  9. return out
  10. }

第二个 stage ,sq,从一个 channel 中接收整数并返回用于发送每个所收到整数的平方的 channel。在输入 channel 已关闭且这个 stage 也发送所有值给下游后,它关闭输出 channel:

The second stage, sq, receives integers from a channel and returns a channel that emits the square of each received integer. After the inbound channel is closed and this stage has sent all the values downstream, it closes the outbound channel:

  1. func sq(in <-chan int) <-chan int {
  2. out := make(chan int)
  3. go func() {
  4. for n := range in {
  5. out <- n * n
  6. }
  7. close(out)
  8. }()
  9. return out
  10. }

main函数设置 pipeline 并运行最终的 stage:它从第二个 stage 接收接受并且输出每个值,直到 channel 被关闭:

The main function sets up the pipeline and runs the final stage: it receives values from the second stage and prints each one, until the channel is closed:

  1. func main() {
  2. // Set up the pipeline.
  3. c := gen(2, 3)
  4. out := sq(c)
  5. // Consume the output.
  6. fmt.Println(<-out) // 4
  7. fmt.Println(<-out) // 9
  8. }

因为 sq的输入输出 channel 是相同类型的,所以我们可以将其组合任意次。我们也可以重写main为一个 range 循环,就像其他 stage 一样:

Since sq has the same type for its inbound and outbound channels, we can compose it any number of times. We can also rewrite main as a range loop, like the other stages:

  1. func main() {
  2. // Set up the pipeline and consume the output.
  3. for n := range sq(sq(gen(2, 3))) {
  4. fmt.Println(n) // 16 then 81
  5. }
  6. }

扇出 Fan-out, 扇入 fan-in

多个函数可以从同一个 channel 读取,直到该 channel 关闭;这称为扇出 (fan-out)。这提供了一种在一组工作线程中分配工作以并行化 CPU 使用和 I/O 的方法。

Multiple functions can read from the same channel until that channel is closed; this is called fan-out. This provides a way to distribute work amongst a group of workers to parallelize CPU use and I/O.

一个函数可以从多个输入读取并处理数据,并通过将输入 channel 多路复用到一个 channel 上,直到所有 input channel 全部关闭为止,这称之为扇入 (fan-in) 。

A function can read from multiple inputs and proceed until all are closed by multiplexing the input channels onto a single channel that’s closed when all the inputs are closed. This is called fan-in.

我们可以改变我们的 pipeline 以运行两个sq实例,每个都从相同的输入 channel 读取。我们引入一个新函数,merge去 fan in 结果:

We can change our pipeline to run two instances of sq, each reading from the same input channel. We introduce a new function, merge, to fan in the results:

  1. func main() {
  2. in := gen(2, 3)
  3. // Distribute the sq work across two goroutines that both read from in.
  4. c1 := sq(in)
  5. c2 := sq(in)
  6. // Consume the merged output from c1 and c2.
  7. for n := range merge(c1, c2) {
  8. fmt.Println(n) // 4 then 9, or 9 then 4
  9. }
  10. }

merge函数通过为每个输入 channel 启动一个 goroutines, 复制值到共享的输出 channel ,把 changel 的列表转换为一个单 channel。一旦所有输出 goroutines 被启动,merge将再启动一个 goroutine 以便在该输出 channel 上的所有发送完成后关闭该 channel 。
在已关闭的 channel 上发送会导致 panic,所以在调用 close 前确保所有发送均完成十分重要。[sync.WaitGroup](https://go.dev/pkg/sync/#WaitGroup)类型提供一个简单的方式去安排这种同步:

The merge function converts a list of channels to a single channel by starting a goroutine for each inbound channel that copies the values to the sole outbound channel. Once all the output goroutines have been started, merge starts one more goroutine to close the outbound channel after all sends on that channel are done. Sends on a closed channel panic, so it’s important to ensure all sends are done before calling close. The sync.WaitGroup type provides a simple way to arrange this synchronization:

  1. func merge(cs ...<-chan int) <-chan int {
  2. var wg sync.WaitGroup // IMPORTANT
  3. out := make(chan int)
  4. // Start an output goroutine for each input channel in cs. output
  5. // copies values from c to out until c is closed, then calls wg.Done.
  6. output := func(c <-chan int) {
  7. for n := range c {
  8. out <- n
  9. }
  10. wg.Done() // IMPORTANT
  11. }
  12. wg.Add(len(cs)) // IMPORTANT
  13. for _, c := range cs {
  14. go output(c)
  15. }
  16. // Start a goroutine to close out once all the output goroutines are
  17. // done. This must start after the wg.Add call.
  18. go func() {
  19. wg.Wait() // IMPORTANT
  20. close(out)
  21. }()
  22. return out
  23. }

止损 Stopping short

我们的 pipeline 函数中有一种模式:

  • 当所有发送操作完成后,stages 关闭他们的输出channel
  • 直到输入 channel 关闭前,stages 会从中持续接收值

    There is a pattern to our pipeline functions:

    • stages close their outbound channels when all the send operations are done.
    • stages keep receiving values from inbound channels until those channels are closed.

这个模式使得每个接收 stage 被写成一个 range 循环,并保证一但所有值都被成功发送到下游,退出所有 goroutine
但在现实的 pipeline 中,stage 并不总是会接收所有的输入值。有时,这是由设计决定的:可能接收者只需要所有值的一个子集去工作。更一般的,一个会 stage 因为在更前面的 stage 中产生的代表 error 的输入值而提前退出。
在哪种情况下,接收者都不应该等待剩下的值到达,我们希望前面的 stage 停止产生后面 stage 不需要的值。
在我们的示例 pipeline 中,如果一个 stage 没能消费所有都输入值,则尝试发送那些值的 goroutine 将无限期地阻塞:

This pattern allows each receiving stage to be written as a range loop and ensures that all goroutines exit once all values have been successfully sent downstream. But in real pipelines, stages don’t always receive all the inbound values. Sometimes this is by design: the receiver may only need a subset of values to make progress. More often, a stage exits early because an inbound value represents an error in an earlier stage. In either case the receiver should not have to wait for the remaining values to arrive, and we want earlier stages to stop producing values that later stages don’t need. In our example pipeline, if a stage fails to consume all the inbound values, the goroutines attempting to send those values will block indefinitely:

  1. // Consume the first value from the output.
  2. out := merge(c1, c2)
  3. fmt.Println(<-out) // 4 or 9
  4. return
  5. // Since we didn't receive the second value from out,
  6. // one of the output goroutines is hung attempting to send it.
  7. }

这是一个资源泄漏:goroutines 消耗内存和运行时资源,goroutines 栈中的堆引用使得数据不能被 GC。 Goroutines 也就不能被 GC 。他们必须自己退出。
我们要改变 pipeline 的上游 stage 使得即使下游 stage 没能接受所有输入值,上游 stage 也能退出。一种实现方式是为输出 channel 添加 buffer 。 buffer 可以持有固定数量的值;如果 buffer 中还有空间,发送会立即完成:

This is a resource leak: goroutines consume memory and runtime resources, and heap references in goroutine stacks keep data from being garbage collected. Goroutines are not garbage collected; they must exit on their own. We need to arrange for the upstream stages of our pipeline to exit even when the downstream stages fail to receive all the inbound values. One way to do this is to change the outbound channels to have a buffer. A buffer can hold a fixed number of values; send operations complete immediately if there’s room in the buffer:

  1. c := make(chan int, 2) // buffer size 2
  2. c <- 1 // succeeds immediately
  3. c <- 2 // succeeds immediately
  4. c <- 3 // blocks until another goroutine does <-c and receives 1

当在 channel 创建的时候就知道要发送值的数量时,一个 buffer 可以简化代码。例如,我们可以重写gen以复制整数列表到一个带有 buffer 的 channel 中,已避免创建新的 goroutine :

When the number of values to be sent is known at channel creation time, a buffer can simplify the code. For example, we can rewrite gen to copy the list of integers into a buffered channel and avoid creating a new goroutine:

  1. func gen(nums ...int) <-chan int {
  2. out := make(chan int, len(nums))
  3. for _, n := range nums {
  4. out <- n
  5. }
  6. close(out)
  7. return out
  8. }

回到我们 pipeline 中被阻塞的 goroutines ,我们可能考虑给merge返回到输出 channel 添加一个 buffer :

Returning to the blocked goroutines in our pipeline, we might consider adding a buffer to the outbound channel returned by merge:

  1. func merge(cs ...<-chan int) <-chan int {
  2. var wg sync.WaitGroup
  3. out := make(chan int, 1) // enough space for the unread inputs
  4. // ... the rest is unchanged ...

虽然这修复了此程序中被阻塞的 goroutine,但这是糟糕的代码。这里缓冲大小为 1 的选择依赖于知道 merge将要接受值的数量和下游 stage 将要消费值的数量。这是脆弱的:如果我们的 gen 多传一些值,或者下游 stage 读取少读一些值,我们的 goroutines 将被再次阻塞。
相反,我们需要提供一种方法,使得下游 stage 可以告诉发送者他们将要停止接收输入。

While this fixes the blocked goroutine in this program, this is bad code. The choice of buffer size of 1 here depends on knowing the number of values merge will receive and the number of values downstream stages will consume. This is fragile: if we pass an additional value to gen, or if the downstream stage reads any fewer values, we will again have blocked goroutines. Instead, we need to provide a way for downstream stages to indicate to the senders that they will stop accepting input.

显示取消 Explicit cancellation

当 main决定不从输出接收所有值就退出,一定要告诉上游 stage 的 goroutine 丢弃它们在尝试发送的值。这可以通过在一个称为done的 channel 上发送值来实现。它发送两个值,因为有两个可能被阻塞的发送者:

When main decides to exit without receiving all the values from out, it must tell the goroutines in the upstream stages to abandon the values they’re trying to send. It does so by sending values on a channel called done. It sends two values since there are potentially two blocked senders:

  1. func main() {
  2. in := gen(2, 3)
  3. // Distribute the sq work across two goroutines that both read from in.
  4. c1 := sq(in)
  5. c2 := sq(in)
  6. // Consume the first value from output.
  7. done := make(chan struct{}, 2)
  8. out := merge(done, c1, c2)
  9. fmt.Println(<-out) // 4 or 9
  10. // Tell the remaining senders we're leaving.
  11. done <- struct{}{}
  12. done <- struct{}{}
  13. }

发送 goroutines 将其发送操作替换为 select 语句,该语句在会在发送操作发生或从 done 接收值时继续。done的值类型是一个空结构体,因为这个值并不关心类型:而是这个接收事件表明在输出上的发送应该被遗弃。输出 goroutines 在它们的输入 channel 上持续循环,所以上游 stage 不会被阻塞。(我们将讨论在某时刻如何允许这个循环提前返回。)

The sending goroutines replace their send operation with a select statement that proceeds either when the send on out happens or when they receive a value from done.The value type of done is the empty struct because the value doesn’t matter: it is the receive event that indicates the send on out should be abandoned. The output goroutines continue looping on their inbound channel, c, so the upstream stages are not blocked. (We’ll discuss in a moment how to allow this loop to return early.)

  1. func merge(done <-chan struct{}, cs ...<-chan int) <-chan int {
  2. var wg sync.WaitGroup
  3. out := make(chan int)
  4. // Start an output goroutine for each input channel in cs. output
  5. // copies values from c to out until c is closed or it receives a value
  6. // from done, then output calls wg.Done.
  7. output := func(c <-chan int) {
  8. for n := range c {
  9. select {
  10. case out <- n:
  11. case <-done:
  12. }
  13. }
  14. wg.Done()
  15. }
  16. // ... the rest is unchanged ...

这个方案有一个问题:每个下游接收者需要知道可能阻塞上游发送者的数量并设置信号通知发送者提前返回。持续跟踪这些计数器既繁琐又容易出错。
我们需要一种方方案去通知一个未知、未绑定数量的 goroutines 停止向下游发送他们的值。在 Go 中,我们可以通过关闭一个channel 来实现,因为在一个已关闭 channel 上的接收操作总是会被立即处理,从而产生对应元素类型的零值。
这意味着main可以简单地通过关闭done channel 实现不阻塞所有的发送者。close操作是一个十分有效地广播给发送者的信号。我拓展我们的每个 pipeline 函数以将done作为一个参数接收并安排close操作通过一个 defer语句触发,这样所有main的返回路径将通知 pipeline 的其他 stage 退出。

This approach has a problem: each downstream receiver needs to know the number of potentially blocked upstream senders and arrange to signal those senders on early return. Keeping track of these counts is tedious and error-prone. We need a way to tell an unknown and unbounded number of goroutines to stop sending their values downstream. In Go, we can do this by closing a channel, because a receive operation on a closed channel can always proceed immediately, yielding the element type’s zero value. This means that main can unblock all the senders simply by closing the done channel. This close is effectively a broadcast signal to the senders. We extend each of our pipeline functions to accept done as a parameter and arrange for the close to happen via a defer statement, so that all return paths from main will signal the pipeline stages to exit.

  1. func main() {
  2. // Set up a done channel that's shared by the whole pipeline,
  3. // and close that channel when this pipeline exits, as a signal
  4. // for all the goroutines we started to exit.
  5. done := make(chan struct{})
  6. defer close(done)
  7. in := gen(done, 2, 3)
  8. // Distribute the sq work across two goroutines that both read from in.
  9. c1 := sq(done, in)
  10. c2 := sq(done, in)
  11. // Consume the first value from output.
  12. out := merge(done, c1, c2)
  13. fmt.Println(<-out) // 4 or 9
  14. // done will be closed by the deferred call.
  15. }

一旦 done 被关闭,我们 pipeline 的每个 stage 现在可以立即返回。merge中的输出例程可以不排空他的输入 channel 就返回,因为它知道上游发送者 sq在done关闭时将停止尝试发送。输出通过一个 defer 语句确保在所有返回路径上调用wg.Done: :::info 此处返回路径应该是指,一段程序中可能有多个不同路径走到 return语句 :::

Each of our pipeline stages is now free to return as soon as done is closed. The output routine in merge can return without draining its inbound channel, since it knows the upstream sender, sq, will stop attempting to send when done is closed. output ensures wg.Done is called on all return paths via a defer statement:

  1. func merge(done <-chan struct{}, cs ...<-chan int) <-chan int {
  2. var wg sync.WaitGroup
  3. out := make(chan int)
  4. // Start an output goroutine for each input channel in cs. output
  5. // copies values from c to out until c or done is closed, then calls
  6. // wg.Done.
  7. output := func(c <-chan int) {
  8. defer wg.Done()
  9. for n := range c {
  10. select {
  11. case out <- n:
  12. case <-done:
  13. return
  14. }
  15. }
  16. }
  17. // ... the rest is unchanged ...

同样的,一旦done被关闭,sq可以立即返回。sq通过defer语句确保他的输出 channel 在所有返回路径都会被关闭:
下面是一些构建 pipeline 的指导准则:

  • 当所有发送操作完成,stage 关闭他们的输出 channel
  • stage 从输入 channel 接收输入值,直到那些 channel 被关闭或发送者被接触阻塞为止。

pipeline 通过确保被有足够的缓冲存储所有发送的值,或当接收者可能丢弃该 channel 时显式通知发送者,从而解除发送者的阻塞。

Similarly, sq can return as soon as done is closed. sq ensures its out channel is closed on all return paths via a defer statement: Here are the guidelines for pipeline construction:

  • stages close their outbound channels when all the send operations are done.
  • stages keep receiving values from inbound channels until those channels are closed or the senders are unblocked.

Pipelines unblock senders either by ensuring there’s enough buffer for all the values that are sent or by explicitly signalling senders when the receiver may abandon the channel.

计算文件树的摘要 Digesting a tree

让我们考虑一些更现实的 pipeline 。
MD5 是一个用于文件校验和的消息摘要算法。命令行工具 md5sum 输出文件列表的摘要值。

Let’s consider a more realistic pipeline. MD5 is a message-digest algorithm that’s useful as a file checksum. The command line utility md5sum prints digest values for a list of files.

  1. % md5sum *.go
  2. d47c2bbc28298ca9befdfbc5d3aa4e65 bounded.go
  3. ee869afd31f83cbb2d10ee81b2b831dc parallel.go
  4. b88175e65fdcbc01ac08aaf1fd9b5e96 serial.go

我们的示例程序类似于md5sum,但是使用单个目录作为参数,并打印该目录下每个常规文件的摘要值,按路径名排序。

Our example program is like md5sum but instead takes a single directory as an argument and prints the digest values for each regular file under that directory, sorted by path name.

  1. % go run serial.go .
  2. d47c2bbc28298ca9befdfbc5d3aa4e65 bounded.go
  3. ee869afd31f83cbb2d10ee81b2b831dc parallel.go
  4. b88175e65fdcbc01ac08aaf1fd9b5e96 serial.go

我们程序的main函数调用一个辅助函数MD5All,MD5All返回一个 映射路径名到摘要值的 map ,然后排序并输出结果:

The main function of our program invokes a helper function MD5All, which returns a map from path name to digest value, then sorts and prints the results:

  1. func main() {
  2. // Calculate the MD5 sum of all files under the specified directory,
  3. // then print the results sorted by path name.
  4. m, err := MD5All(os.Args[1])
  5. if err != nil {
  6. fmt.Println(err)
  7. return
  8. }
  9. var paths []string
  10. for path := range m {
  11. paths = append(paths, path)
  12. }
  13. sort.Strings(paths)
  14. for _, path := range paths {
  15. fmt.Printf("%x %s\n", m[path], path)
  16. }
  17. }

我们主要讨论MD5All函数。在[serial.go](https://go.dev/blog/pipelines/serial.go)中,实现不用并发,只是在遍历树时读取并汇总每个文件。

The MD5All function is the focus of our discussion. In serial.go, the implementation uses no concurrency and simply reads and sums each file as it walks the tree.

  1. // MD5All reads all the files in the file tree rooted at root and returns a map
  2. // from file path to the MD5 sum of the file's contents. If the directory walk
  3. // fails or any read operation fails, MD5All returns an error.
  4. func MD5All(root string) (map[string][md5.Size]byte, error) {
  5. m := make(map[string][md5.Size]byte)
  6. err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
  7. if err != nil {
  8. return err
  9. }
  10. if !info.Mode().IsRegular() {
  11. return nil
  12. }
  13. data, err := ioutil.ReadFile(path)
  14. if err != nil {
  15. return err
  16. }
  17. m[path] = md5.Sum(data)
  18. return nil
  19. })
  20. if err != nil {
  21. return nil, err
  22. }
  23. return m, nil
  24. }

并行摘要 Parallel digestion

在 [parallel.go](https://go.dev/blog/pipelines/parallel.go)中,我们将MD5All分为两个 stage 的 pipeline 。第一个 stage ,sumFiles,遍历树,然后在一个新 goroutine 中计算摘要,并发送结果到带有结果值类型的 channel 上:

In parallel.go, we split MD5All into a two-stage pipeline. The first stage, sumFiles, walks the tree, digests each file in a new goroutine, and sends the results on a channel with value type result:

  1. type result struct {
  2. path string
  3. sum [md5.Size]byte
  4. err error
  5. }

sumFiles返回两个 channel :一个用于结果,另外一个用于 filepath.Walk返回的错误。便利函数启动一个新 goroutine 去处理每个常规文件,然后检查done。如果done被关闭,遍历立即停止:

sumFiles returns two channels: one for the results and another for the error returned by filepath.Walk. The walk function starts a new goroutine to process each regular file, then checks done. If done is closed, the walk stops immediately:

  1. func sumFiles(done <-chan struct{}, root string) (<-chan result, <-chan error) {
  2. // For each regular file, start a goroutine that sums the file and sends
  3. // the result on c. Send the result of the walk on errc.
  4. c := make(chan result)
  5. errc := make(chan error, 1)
  6. go func() {
  7. var wg sync.WaitGroup
  8. err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
  9. if err != nil {
  10. return err
  11. }
  12. if !info.Mode().IsRegular() {
  13. return nil
  14. }
  15. wg.Add(1)
  16. go func() {
  17. data, err := ioutil.ReadFile(path)
  18. select {
  19. case c <- result{path, md5.Sum(data), err}:
  20. case <-done:
  21. }
  22. wg.Done()
  23. }()
  24. // Abort the walk if done is closed.
  25. select {
  26. case <-done:
  27. return errors.New("walk canceled")
  28. default:
  29. return nil
  30. }
  31. })
  32. // Walk has returned, so all calls to wg.Add are done. Start a
  33. // goroutine to close c once all the sends are done.
  34. go func() {
  35. wg.Wait()
  36. close(c)
  37. }()
  38. // No select needed here, since errc is buffered.
  39. errc <- err
  40. }()
  41. return c, errc
  42. }

MD5All从c.MD5All接受摘要值,在error时返回,通过defer关闭done:

MD5All receives the digest values from c. MD5All returns early on error, closing done via a defer:

  1. func MD5All(root string) (map[string][md5.Size]byte, error) {
  2. // MD5All closes the done channel when it returns; it may do so before
  3. // receiving all the values from c and errc.
  4. done := make(chan struct{})
  5. defer close(done)
  6. c, errc := sumFiles(done, root)
  7. m := make(map[string][md5.Size]byte)
  8. for r := range c {
  9. if r.err != nil {
  10. return nil, r.err
  11. }
  12. m[r.path] = r.sum
  13. }
  14. if err := <-errc; err != nil {
  15. return nil, err
  16. }
  17. return m, nil
  18. }

有界并行 Bounded parallelism

[parallel.go](https://go.dev/blog/pipelines/parallel.go)中实现的MD5All为每个文件启动一个新 goroutine 。在一个有许多大文件的目录中,这可能导致分配的内存多于机器可用的内存。
我们可以通过限制并行读取的文件数目来限制这样的分配。在[bounded.go](https://go.dev/blog/pipelines/bounded.go)中,我么通过创建固定数量读取文件的 goroutine 来实现。我们的管道现在有三个 stage : 遍历树,读取文件并计算摘要,收集摘要。
第一个 stage ,walkFiles发送文件树中的一般文件的路径:

The MD5All implementation in parallel.go starts a new goroutine for each file. In a directory with many large files, this may allocate more memory than is available on the machine. We can limit these allocations by bounding the number of files read in parallel. In bounded.go, we do this by creating a fixed number of goroutines for reading files. Our pipeline now has three stages: walk the tree, read and digest the files, and collect the digests. The first stage, walkFiles, emits the paths of regular files in the tree:

  1. func walkFiles(done <-chan struct{}, root string) (<-chan string, <-chan error) {
  2. paths := make(chan string)
  3. errc := make(chan error, 1)
  4. go func() {
  5. // Close the paths channel after Walk returns.
  6. defer close(paths)
  7. // No select needed for this send, since errc is buffered.
  8. errc <- filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
  9. if err != nil {
  10. return err
  11. }
  12. if !info.Mode().IsRegular() {
  13. return nil
  14. }
  15. select {
  16. case paths <- path:
  17. case <-done:
  18. return errors.New("walk canceled")
  19. }
  20. return nil
  21. })
  22. }()
  23. return paths, errc
  24. }

中间 stage 启动一个固定数量的digester goroutine,这些 goroutine 从paths接受文件名并发送结果到cchannel:

The middle stage starts a fixed number of digester goroutines that receive file names from paths and send results on channel c:

  1. func digester(done <-chan struct{}, paths <-chan string, c chan<- result) {
  2. for path := range paths {
  3. data, err := ioutil.ReadFile(path)
  4. select {
  5. case c <- result{path, md5.Sum(data), err}:
  6. case <-done:
  7. return
  8. }
  9. }
  10. }

不同于我们之前的例子,digester不关闭它的输出 channel ,因为多个 goroutine 会在一个共享的 channel 上发送。相反,MD5All的代码则安排这个 channel 在所有digester完成的时候关闭:

Unlike our previous examples, digester does not close its output channel, as multiple goroutines are sending on a shared channel. Instead, code in MD5All arranges for the channel to be closed when all the digesters are done:

  1. // Start a fixed number of goroutines to read and digest files.
  2. c := make(chan result)
  3. var wg sync.WaitGroup
  4. const numDigesters = 20
  5. wg.Add(numDigesters)
  6. for i := 0; i < numDigesters; i++ {
  7. go func() {
  8. digester(done, paths, c)
  9. wg.Done()
  10. }()
  11. }
  12. go func() {
  13. wg.Wait()
  14. close(c)
  15. }()

我们可以不用每个digester创建并返回它自己的输出 channel ,这样我们就需要一个额外的 goroutine 去扇入结果。
最终 stage 接收所有从 c 发来的结果然后检查从errc发来的 error 。这个检查不能提前,因为在这点之前,walkFiles可能阻塞发送值到下游:

We could instead have each digester create and return its own output channel, but then we would need additional goroutines to fan-in the results. The final stage receives all the results from c then checks the error from errc. This check cannot happen any earlier, since before this point, walkFiles may block sending values downstream:

  1. m := make(map[string][md5.Size]byte)
  2. for r := range c {
  3. if r.err != nil {
  4. return nil, r.err
  5. }
  6. m[r.path] = r.sum
  7. }
  8. // Check whether the Walk failed.
  9. if err := <-errc; err != nil {
  10. return nil, err
  11. }
  12. return m, nil
  13. }

总结 Conclusion

这篇文章展示了在 Go 中构建流数据 pipeline 的技术。在这样的 pipeline 中处理失败是棘手的,因为 pipeline 中的每个 stage 可能因尝试发送值到下游而阻塞,但下游 stage 可能不再关心输入数据。我们展示了如何关闭 channel 使得可以广播一个 “done” 信号通知所有该 pipeline 启动的 goroutine 并定义了正确构建 pipeline 的指导准则。

This article has presented techniques for constructing streaming data pipelines in Go. Dealing with failures in such pipelines is tricky, since each stage in the pipeline may block attempting to send values downstream, and the downstream stages may no longer care about the incoming data. We showed how closing a channel can broadcast a “done” signal to all the goroutines started by a pipeline and defined guidelines for constructing pipelines correctly.

深入阅读: