亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go lang,通道處理序列

Go lang,通道處理序列

Go
慕碼人8056858 2021-11-01 16:33:10
我正在通過'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 例程和通道。
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號