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

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

Goroutine inside for loop takes only the last value of slice

问题

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

package main

import (
	"fmt"
	"time"
)

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

这段代码输出以下内容:

value is  5
value is  5
value is  5
value is  5
value is  5

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

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

英文:

Can anyone explain this behavior to me?

package main

import (
	"fmt"
	"time"
)

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

this code prints the following output.

value is  5
value is  5
value is  5
value is  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。
如果你想要获取不同的切片值,可以像这样做:

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

输出结果是:

value is 1
value is 2
value is 3
value is 4
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:

func main() {
a := []int64{1, 2, 3, 4, 5}
for _,v := range a {
	v2 := v
	go func(){
		fmt.Println("value is ", v2)
	}()

}
time.Sleep(2*time.Second)

}

Output is:

value is  1
value is  2
value is  3
value is  4
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:

确定