【发布时间】:2015-08-24 01:38:52
【问题描述】:
我正在通过'A tour of Go'学习Go lang,很难理解Go频道运行顺序,
package main
import "fmt"
import "time"
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
time.Sleep(1000 * time.Millisecond)
sum += v
}
c <- sum // send sum to c
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
fmt.Println("Print this first,")
}
如果在代码之上运行,我预计,
Print this first,
17 -5 12
因为,Go 例程以非阻塞方式运行,但实际上它会打印,
17 -5 12
Print this first,
我在网上找到的另一个例子,
package main
import "fmt"
type Data struct {
i int
}
func func1(c chan *Data ) {
fmt.Println("Called")
for {
var t *Data;
t = <-c //receive
t.i += 10 //increment
c <- t //send it back
}
}
func main() {
c := make(chan *Data)
t := Data{10}
go func1(c)
println(t.i)
c <- &t //send a pointer to our t
i := <-c //receive the result
println(i.i)
println(t.i)
}
另外,我预计,它会先打印“Called”,但结果是
10
20
20
Called
我误会了什么?请帮助我了解 Go 例程和通道。
【问题讨论】:
-
避免使用内置的
print/println,因为实现与fmt不同。更好的是,如果您正在调试任何并发,请使用log,因为它会序列化并发调用,并且可以自动添加时间戳、文件名等。
标签: go