日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Golang?channel為什么不會阻塞的原因詳解_Golang

作者:燒麥?212 ? 更新時間: 2022-09-21 編程語言

正文

最近在學通道channel,發(fā)現(xiàn)一個簡單的demo:

package main
import "fmt"
func main() {
    chanInt := make(chan int)
    go func() {
        chanInt <- 100
    }()
    res := <-chanInt
    fmt.Println(res)
}

輸出結果是100,這個沒有問題。但是之前在學goroutine的時候有看到過一個例子:

package main
import "fmt"
func hello() {
    fmt.Println("Hello Goroutine!")
}
func main() {
    go hello() // 啟動另外一個goroutine去執(zhí)行hello函數(shù)
    fmt.Println("main goroutine done!")
}

這個例子輸出的只有:main goroutine done! 并沒有Hello Goroutine!

看過解釋:在程序啟動時,Go程序就會為main()函數(shù)創(chuàng)建一個默認的goroutine。當main()函數(shù)返回的時候該goroutine就結束了,所有在main()函數(shù)中啟動的goroutine會一同結束

那么這個解釋放到第一個例子為什么不適用了?

ps:我得理解是:運行到res := <-chanInt這句會阻塞,直到協(xié)程寫入通道后,就馬上讀取,繼續(xù)執(zhí)行打印語句。不知道理解的對不對?

然后就是關于阻塞的情況,比如我把第一個例子改一下:

package main
import (
    "fmt"
    "time"
)
func main() {
    chanInt := make(chan int)
    go func() {
        chanInt &lt;- 100
    }()
    time.Sleep(10 * time.Second)
    res := &lt;-chanInt
    fmt.Println(res)
}

多了time.Sleep(10 * time.Second)等待10秒鐘,10秒后輸出100,這個沒有問題。

然后再看一個例子:

func main() {
    chanInt := make(chan int)
    chanInt &lt;- 100
    res := &lt;-chanInt
    fmt.Println(res)
}

原文鏈接:https://segmentfault.com/q/1010000040414910

欄目分類
最近更新