英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论