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

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

當沒有線路調用它時,控制如何轉到主 goroutine?

當沒有線路調用它時,控制如何轉到主 goroutine?

Go
慕碼人2483693 2022-06-06 16:08:48
// _Closing_ a channel indicates that no more values// will be sent on it. This can be useful to communicate// completion to the channel's receivers.package mainimport "fmt"// In this example we'll use a `jobs` channel to// communicate work to be done from the `main()` goroutine// to a worker goroutine. When we have no more jobs for// the worker we'll `close` the `jobs` channel.func main() {    jobs := make(chan int, 5)    done := make(chan bool)    fmt.Println("1")    go func() {        for {                fmt.Println("4")            j, more := <-jobs            if more {                fmt.Println("received job", j)            } else {                fmt.Println("received all jobs")                done <- true                return            }        }    }()    fmt.Println("2")    // This sends 3 jobs to the worker over the `jobs`    // channel, then closes it.    for j := 1; j <= 3; j++ {            fmt.Println("3", j)        jobs <- j        fmt.Println("sent job", j)    }    fmt.Println("5")    close(jobs)    fmt.Println("6")    fmt.Println("sent all jobs")    //How does control go from here to the main's go routine - line 18. Who call's it? and How?    // We await the worker using the    // [synchronization](channel-synchronization) approach    // we saw earlier.    <-done    fmt.Println("7")}https://play.golang.org/p/Xe_wh3YTmwk控制如何從第 46 行轉到第 18 行?
查看完整描述

1 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

當您將 Go 應用程序編譯為可執行二進制文件時,編譯器會在二進制文件中包含一個運行時。運行您的應用程序時,此運行時負責調度和運行 goroutine。

在第 17 行中,您啟動了一個 goroutine,因此運行時將安排與maingoroutine 并發運行它,并且可能并行運行(如果有足夠的內核并且 GOMAXPROCS 允許,有關詳細信息,請參閱Concurrency is not parallelism)。

規范:Go 語句:

函數值和參數在調用 goroutine 中像往常一樣被評估,但與常規調用不同,程序執行不會等待調用的函數完成。相反,該函數開始在一個新的 goroutine 中獨立執行。當函數終止時,它的 goroutine 也會終止。如果函數有任何返回值,它們會在函數完成時被丟棄。


查看完整回答
反對 回復 2022-06-06
  • 1 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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