1 回答
TA贡献2012条经验 获得超12个赞
在您的第一个示例中,输出应为-5 17 12或17 -5 12。两个 goroutine 同时(同时)运行。哪个 goroutine 先完成的结果将存储在变量中x。另一个 goroutine 的结果存储在y. 为了更好地看到 goroutines 是并发运行的,你可以在 function 里面放一个随机计时器sum()。这样,您应该会看到不同运行之间的输出变化,因为一个 goroutine 随机花费的时间比另一个更长:
package main
import (
"fmt"
"time"
"math/rand"
)
func sum(a []int, c chan int) {
time.Sleep(time.Duration(rand.Intn(1000000))) // wait for up to 1ms
total := 0
for _, v := range a {
total += v
}
c <- total
}
func main() {
rand.Seed(time.Now().Unix())
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x := <-c
y := <-c
fmt.Println(x, y, x+y)
}
在您的第二个示例中,您正在启动第一个 goroutine。然后你从 channel 中读取c,这是一个阻塞操作(意味着它会等待直到有结果 => 第一个 goroutine 完成)。此处的输出是确定性的,并且始终为17 -5 12。
- 1 回答
- 0 关注
- 310 浏览
添加回答
举报