我正在通过'A tour of Go'学习Go lang,很难理解Go channel运行序列,
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)
}
此外,我预计,它首先打印“调用”,但结果是
10
20
20
Called
我误解了什么?请帮助我理解 Go 例程和通道。
相关分类