当我添加表达式 "fmt.Println()" 时发生了什么
what happended when I add the expression "fmt.Println()"
我对 golang 很感兴趣,在探索频道的过程中,我对以下代码感到困惑,所以有人可以告诉我它们之间的区别吗?
当我 运行 代码时,控制台记录 -5,17
如果我使用评论,我会得到不同的结果 17,-5
我不知道发生了什么...
golang版本是最新的
//comman func
func sum(a []int, c chan int) {
total := 0
for _, v := range a {
total += v
}
c <- total // send total to c
}
func main (){
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
//fmt.Println(a[:len(a)/2])
go sum(a[len(a)/2:], c)
//fmt.Println(a[len(a)/2:])
gh,w33 := <-c, <-c
fmt.Println(gh,w33)
}
我希望两次结果是17,-5,但是当注释没有用时,结果是-5 17
golang 使用调度程序来调度 go routines。
您可以在此处阅读更多相关信息 https://povilasv.me/go-scheduler/
所以当你运行上面的程序。不确定 goroutines 是否会按照您编写的顺序执行。
我对 golang 很感兴趣,在探索频道的过程中,我对以下代码感到困惑,所以有人可以告诉我它们之间的区别吗?
当我 运行 代码时,控制台记录 -5,17 如果我使用评论,我会得到不同的结果 17,-5 我不知道发生了什么...
golang版本是最新的
//comman func
func sum(a []int, c chan int) {
total := 0
for _, v := range a {
total += v
}
c <- total // send total to c
}
func main (){
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
//fmt.Println(a[:len(a)/2])
go sum(a[len(a)/2:], c)
//fmt.Println(a[len(a)/2:])
gh,w33 := <-c, <-c
fmt.Println(gh,w33)
}
我希望两次结果是17,-5,但是当注释没有用时,结果是-5 17
golang 使用调度程序来调度 go routines。 您可以在此处阅读更多相关信息 https://povilasv.me/go-scheduler/ 所以当你运行上面的程序。不确定 goroutines 是否会按照您编写的顺序执行。