我正在通過'A tour of Go'學習Go lang,很難理解Go channel運行序列,package mainimport "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 12Print this first,我在網上找到的另一個例子,package mainimport "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)}此外,我預計,它首先打印“調用”,但結果是102020Called我誤解了什么?請幫助我理解 Go 例程和通道。
Go lang,通道處理序列
慕碼人8056858
2021-11-01 16:33:10