请检查此代码段:
values := []field{{"one"},{"two"},{"three"}}
for _, v := range values {
go v.print()
}
此处链接:https://play.golang.org/p/cdryPmyWt5
上面的代码将检查for循环中指针和值之间的差异,而go语句也同时使用。代码:
poniters := []*field{{"one"},{"two"},{"three"}}
for _, v := range poniters {
go v.print()
}
我们知道控制台将打印三个三个作为结果,因为for循环在goroutines开始执行之前运行到结尾,这将v写为切片的最后一个元素。但指针怎么样?
{{1}}
似乎打印一两三,为什么?
感谢。
答案 0 :(得分:6)
答:在调用函数之前评估参数。在对它们进行求值之后,调用的参数将通过值传递给函数,并且被调用的函数开始执行,因此:
第一个go v.print()
是go (*field).print(&v)
和
的语法糖
第二个go v.print()
是go (*field).print(v)
的语法糖。
如果在goroutines开始之前第一个for
循环结束,则&v
对于呼叫是相同的,并且这三个呼叫都是相同的。通过在time.Sleep(100)
之后将go v.print()
添加到第一个循环来查看代码2。或The Go Playground (Code 3 with sync.WaitGroup
)上的go func(v field) { v.print() }(v)
此外,您还有数据竞争(参见B)。
对于第二个go (*field).print(v)
,此处v
是指针,在调用print
之前评估了三个goroutines参数,有三个不同的地址。
package main
import (
"fmt"
"time"
)
type field struct {
name string
}
func (p *field) print() {
fmt.Println(p.name)
}
func main() {
fmt.Println("use values:")
// use values in range loop and go rountines
values := []field{{"one"}, {"two"}, {"three"}}
for _, v := range values {
fmt.Println(&v)
go (*field).print(&v) //go v.print()
}
time.Sleep(time.Second)
fmt.Println()
fmt.Println("use pointers:")
// use pointers in range loop and go rountines
poniters := []*field{{"one"}, {"two"}, {"three"}}
for _, v := range poniters {
fmt.Println(v)
go (*field).print(v) //go v.print()
}
time.Sleep(time.Second)
}
输出:
use values:
&{one}
&{two}
&{three}
three
three
three
use pointers:
&{one}
&{two}
&{three}
two
one
three
上试试
package main
import (
"fmt"
"time"
)
type field struct {
name string
}
func (p *field) print() {
fmt.Println(p.name)
}
func main() {
fmt.Println("use values:")
// use values in range loop and go rountines
values := []field{{"one"}, {"two"}, {"three"}}
for _, v := range values {
fmt.Println(&v)
go v.print() //go (*field).print(&v) //
time.Sleep(100)
}
time.Sleep(time.Second)
fmt.Println()
fmt.Println("use pointers:")
// use pointers in range loop and go rountines
poniters := []*field{{"one"}, {"two"}, {"three"}}
for _, v := range poniters {
fmt.Println(v)
go v.print() //go (*field).print(v) //
}
time.Sleep(time.Second)
}
输出:
use values:
&{one}
one
&{two}
two
&{three}
three
use pointers:
&{one}
&{two}
&{three}
one
two
three
B:您有数据竞争,请尝试go build -race
your code,然后运行生成的文件WARNING: DATA RACE
:
输出:
use values:
==================
WARNING: DATA RACE
Read at 0x00c042030210 by goroutine 6:
runtime.convT2E()
Go/src/runtime/iface.go:155 +0x0
main.(*field).print()
.../m.go:14 +0x6c
Previous write at 0x00c042030210 by main goroutine:
main.main()
.../m.go:22 +0x1c3
Goroutine 6 (running) created at:
main.main()
.../m.go:23 +0x204
==================
two
three
three
use pointers:
one
two
three
Found 1 data race(s)