[英]Modifying a struct in a goroutine?
I was experimenting with goroutines, and it seems I can't modify the value of a struct within a goroutine (example below). 我正在尝试使用goroutine,但似乎无法修改goroutine中的struct值(下面的示例)。 Is there any work around for this?
有什么解决办法吗?
EDIT: It appears that the code runs if I place a sleep statement, indicating that the goroutines would run if given more time, but they finish running after everything in main() has already executed. 编辑:看来,如果我放置一个sleep语句,代码就会运行,这表明如果有更多的时间,goroutines将运行,但是它们在main()中的所有内容都已执行后才完成运行。 How do I "wait" for my goroutines to finish before proceeding?
如何继续等待我的goroutine完成,然后再继续?
package main
import (
"fmt"
)
type num struct {
val int
}
func (d *num) cube_val() {
fmt.Println("changing value...")
d.val = d.val*d.val*d.val
}
func main() {
a := []num{num{1},num{3},num{2},num{5},num{4}}
for i := range a {
go a[i].cube_val()
}
// code that waits for go routines to finish should get inserted here ...
fmt.Println(a) // change does NOT happen
for i := range a {
a[i].cube_val()
}
fmt.Println(a) // change happens, and fmt.Println statements worked?
}
The changes do happen. 更改确实发生了。 But they happened for you after the
fmt.Println(a)
. 但是他们在
fmt.Println(a)
之后发生了。 In fact there are no guarantees on the execution order of the goroutines and the print statement, without synchronization . 事实上,有是够程和打印语句的执行顺序没有担保, 没有同步 。
If you want the fmt.Println(a)
happen after the goroutines have completed, you have to wait for them, for example: ( see also on Playground ) 如果您希望在goroutine完成后执行
fmt.Println(a)
,则必须等待它们,例如:( 另请参见在Playground上 )
func main() {
var wg sync.WaitGroup
a := []num{num{1}, num{3}, num{2}, num{5}, num{4}}
for i := range a {
wg.Add(1)
go func(d *num) {
defer wg.Done()
d.cube_val()
}(&a[i])
}
wg.Wait()
fmt.Println(a)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.