正文
最近在学通道channel,发现一个简单的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去执行hello函数
    fmt.Println("main goroutine done!")
}
这个例子输出的只有:main goroutine done! 并没有Hello Goroutine!
看过解释:在程序启动时,Go程序就会为main()函数创建一个默认的goroutine。当main()函数返回的时候该goroutine就结束了,所有在main()函数中启动的goroutine会一同结束
那么这个解释放到第一个例子为什么不适用了?
ps:我得理解是:运行到res := <-chanInt这句会阻塞,直到协程写入通道后,就马上读取,继续执行打印语句。不知道理解的对不对?
然后就是关于阻塞的情况,比如我把第一个例子改一下:
package main
import (
    "fmt"
    "time"
)
func main() {
    chanInt := make(chan int)
    go func() {
        chanInt <- 100
    }()
    time.Sleep(10 * time.Second)
    res := <-chanInt
    fmt.Println(res)
}
多了time.Sleep(10 * time.Second)等待10秒钟,10秒后输出100,这个没有问题。
然后再看一个例子:
func main() {
    chanInt := make(chan int)
    chanInt <- 100
    res := <-chanInt
    fmt.Println(res)
}