修改 goroutine 中的结构?
Modifying a struct in a goroutine?
我正在试验 goroutines,似乎我无法修改 goroutine 中结构的值(下面的示例)。有什么解决办法吗?
编辑:如果我放置一个睡眠语句,代码似乎 运行s,表明 goroutines 将 运行 如果有更多时间,但它们在 运行ning 之后完成main() 中的所有内容都已执行。我如何 "wait" 让我的 goroutines 在继续之前完成?
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?
}
确实发生了变化。但它们发生在 fmt.Println(a)
之后。
实际上 goroutines 和 print 语句的执行顺序是没有保证的,without synchronization.
如果你希望 fmt.Println(a)
在 goroutines 完成后发生,你必须等待它们,例如:(see also on 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)
}
我正在试验 goroutines,似乎我无法修改 goroutine 中结构的值(下面的示例)。有什么解决办法吗?
编辑:如果我放置一个睡眠语句,代码似乎 运行s,表明 goroutines 将 运行 如果有更多时间,但它们在 运行ning 之后完成main() 中的所有内容都已执行。我如何 "wait" 让我的 goroutines 在继续之前完成?
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?
}
确实发生了变化。但它们发生在 fmt.Println(a)
之后。
实际上 goroutines 和 print 语句的执行顺序是没有保证的,without synchronization.
如果你希望 fmt.Println(a)
在 goroutines 完成后发生,你必须等待它们,例如:(see also on 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)
}