正文 最近在学通道channel,发现一个简单的demo: package main import "fmt" func main() { chanInt := make(c
最近在学通道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)
}
这个例子就会死锁,阻塞在chanInt <- 100这句,发现没有接收者所以死锁了,这边不理解的是:睡眠10秒的时候,在这10秒里面为什么不会造成死锁?而最后一个例子一运行马上报死锁?更多关于golang channel不会阻塞的资料请关注编程网其它相关文章!
--结束END--
本文标题: Golang channel为什么不会阻塞的原因详解
本文链接: https://www.lsjlt.com/news/120943.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-05
2024-04-05
2024-04-05
2024-04-04
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-04
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0