猿问

gooroutine 是否有优先级?

Golang鱼,求解释。


Goroutine 是否有优先级?


package main


import (

  "fmt"

)


func sum(a []int, c chan int) {

  var total int

  for _, v := range a {

    total += v

  }

  c <- total

}


func main() {

  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, y := <-c, <-c

  x := <-c

  y := <-c

  fmt.Println(x, y, x+y)

}

为什么x是-5 y是17,是不是第一个goroutine被阻塞了?如果


go sum(a[:len(a)/2], c)

x := <-c

go sum(a[len(a)/2:], c)

y := <-c

这个顺序是对的。为什么...


蝴蝶刀刀
浏览 311回答 1
1回答

繁花如伊

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

相关分类

Go
我要回答