From 43672654ca8951ea3fdad49e6f6f514dc67b7826 Mon Sep 17 00:00:00 2001 From: Respawnz <47511522+Respawnz@users.noreply.github.com> Date: Fri, 26 Apr 2019 03:46:37 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=8E=E7=BF=BB=E8=AF=91=E4=B8=8A=E8=B0=83?= =?UTF-8?q?=E6=95=B4=E4=BA=86=E4=B8=80=E4=B8=8B=E8=8B=B1=E6=96=87=E5=8E=9F?= =?UTF-8?q?=E8=91=97=E8=A7=A3=E9=87=8A=E4=B8=AD=E7=9A=84=E5=9B=A0=E6=9E=9C?= =?UTF-8?q?=E9=A1=BA=E5=BA=8F=20(#606)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 建议从翻译上调转了一下英文原著解释中的因果顺序 英文原著: > Notice the use of the closure: the current i, xi are passed to the closure as parameters, masking the i, xi variables from the outer for-loop. This allows each goroutine to have its own copy of i, xi; otherwise, the next iteration of the for-loop would update i, xi in all goroutines. On the other hand, the res slice is not passed to the closure, since each goroutine does not need a separate copy of it. The res slice is part of the closure’s environment but is not a parameter 原译文: >注意闭合:i、xi 都是作为参数传入闭合函数的,从外层循环中隐藏了变量 i 和 xi。让每个协程有一份 i 和 xi 的拷贝;另外,for 循环的下一次迭代会更新所有协程中 i 和 xi 的值。切片 res 没有传入闭合函数,因为协程不需要单独拷贝一份。切片 res 也在闭合函数中但并不是参数。 我的建议: >注意上述代码中闭合函数的用法:`i`、`xi` 都是作为参数传入闭合函数的,这一做法使得每个协程有一份 `i` 和 `xi` 的拷贝,从而向闭合函数内部隐藏了外层循环中的变量 `i` 和 `xi`;否则,for 循环的下一次迭代会更新所有协程中 `i` 和 `xi` 的值。另一方面,切片 `res` 没有传入闭合函数,因为协程不需要`res`的单独拷贝。切片 `res` 也在闭合函数中但并不是参数。 * 增加了译者注和一些用词调整 --- eBook/14.2.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/eBook/14.2.md b/eBook/14.2.md index fd64ffc..00ec986 100644 --- a/eBook/14.2.md +++ b/eBook/14.2.md @@ -302,7 +302,7 @@ go doSort(s[i:]) <-done ``` -下边的代码,用完整的信号量模式对长度为N的 float64 切片进行了 N 个` doSomething()` 计算并同时完成,通道 sem 分配了相同的长度(切包含空接口类型的元素),待所有的计算都完成后,发送信号(通过放入值)。在循环中从通道 sem 不停的接收数据来等待所有的协程完成。 +下边的代码,用完整的信号量模式对长度为N的 float64 切片进行了 N 个` doSomething()` 计算并同时完成,通道 sem 分配了相同的长度(且包含空接口类型的元素),待所有的计算都完成后,发送信号(通过放入值)。在循环中从通道 sem 不停的接收数据来等待所有的协程完成。 ```go type Empty interface {} @@ -322,7 +322,8 @@ for i, xi := range data { for i := 0; i < N; i++ { <-sem } ``` -注意闭合:`i`、`xi` 都是作为参数传入闭合函数的,从外层循环中隐藏了变量 `i` 和 `xi`。让每个协程有一份 `i` 和 `xi` 的拷贝;另外,for 循环的下一次迭代会更新所有协程中 `i` 和 `xi` 的值。切片 `res` 没有传入闭合函数,因为协程不需要单独拷贝一份。切片 `res` 也在闭合函数中但并不是参数。 +注意上述代码中闭合函数的用法:`i`、`xi` 都是作为参数传入闭合函数的,这一做法使得每个协程(译者注:在其启动时)获得一份 `i` 和 `xi` 的单独拷贝,从而向闭合函数内部屏蔽了外层循环中的 `i` 和 `xi`变量;否则,for 循环的下一次迭代会更新所有协程中 `i` 和 `xi` 的值。另一方面,切片 `res` 没有传入闭合函数,因为协程不需要`res`的单独拷贝。切片 `res` 也在闭合函数中但并不是参数。 + ## 14.2.8 实现并行的 for 循环