在for循环中的goroutine只会获取切片的最后一个值。

huangapple go评论104阅读模式
英文:

Goroutine inside for loop takes only the last value of slice

问题

有人能解释一下这个行为吗?

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. a := []int64{1, 2, 3, 4, 5}
  8. for _, v := range a {
  9. go func() {
  10. fmt.Println("value is ", v)
  11. }()
  12. }
  13. time.Sleep(2 * time.Second)
  14. }

这段代码输出以下内容:

  1. value is 5
  2. value is 5
  3. value is 5
  4. value is 5
  5. value is 5

为什么当没有传递输入参数时,goroutine 只取了切片中的最后一个值?

编辑:我只想知道程序的执行方式。每个 goroutine 都有相同的值,但为什么它总是最后一个值?(疑问:goroutine 是否只在循环遍历切片的所有元素后执行?)

英文:

Can anyone explain this behavior to me?

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. a := []int64{1, 2, 3, 4, 5}
  8. for _,v := range a {
  9. go func(){
  10. fmt.Println("value is ", v)
  11. }()
  12. }
  13. time.Sleep(2*time.Second)
  14. }

this code prints the following output.

  1. value is 5
  2. value is 5
  3. value is 5
  4. value is 5
  5. value is 5

Why does the goroutine take only the last value in the slice when no input parameter is passed?

Edit: I just want to know how the program is executing. Every goroutine is having the same value, but why is it always the last value? (Doubt: does goroutine execute only after looping through all the elements in slice? )

答案1

得分: 2

因为每个goroutine都持有相同的变量v。
如果你想要获取不同的切片值,可以像这样做:

  1. func main() {
  2. a := []int64{1, 2, 3, 4, 5}
  3. for _, v := range a {
  4. v2 := v
  5. go func() {
  6. fmt.Println("value is", v2)
  7. }()
  8. }
  9. time.Sleep(2 * time.Second)
  10. }

输出结果是:

  1. value is 1
  2. value is 2
  3. value is 3
  4. value is 4
  5. value is 5
英文:

Because each of the goroutines hold the same variable v.
If you want to take diffrent value of the silce, do like this:

  1. func main() {
  2. a := []int64{1, 2, 3, 4, 5}
  3. for _,v := range a {
  4. v2 := v
  5. go func(){
  6. fmt.Println("value is ", v2)
  7. }()
  8. }
  9. time.Sleep(2*time.Second)

}

Output is:

  1. value is 1
  2. value is 2
  3. value is 3
  4. value is 4
  5. value is 5

huangapple
  • 本文由 发表于 2021年11月16日 14:59:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/69984933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定