gpt4 book ai didi

go - 为什么我们需要在 go routine 中运行无缓冲 channel ,而缓冲 channel 可以在没有 go routine 的情况下工作?

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:21 25 4
gpt4 key购买 nike

我正在阅读有关 gobyexample 的教程。我注意到作者已经展示了使用 go routine 的 gochannel 示例,但在错误的 go channel 中他直接向 channel 发送消息。

我尝试在我的本地系统上运行无缓冲 channel 而不使用 go routine 但它抛出“ fatal error :所有 goroutines 都睡着了 - 死锁!”但是缓冲 channel 在没有 go routine 的情况下工作正常

func channelDemo() {
message := make(chan string)
// go func() {
// message <- "Hello"
// }()
message <- "Hello"
msg := <-message

fmt.Println("msg", msg)
}
func channelBufferingDemo() {
messages := make(chan string, 3)

messages <- "Buffered"
messages <- "channel"
fmt.Println(<-messages)
fmt.Println(<-messages)
}

最佳答案

只有当 channel 可以接受输入时, channel 发送才会成功,也就是说,该 channel 有一个监听器,或者 channel 中有可用的缓冲区。否则,goroutine 将进入休眠状态,直到其中之一变为真:有人开始监听,或者有人从 channel 读取并且现在有缓冲区空间。

对于没有缓冲区的 channel ,您可以写入的唯一方法是有人在听它。如果只有一个 goroutine,如果你写入 channel ,所有的 goroutines 都会休眠。

使用缓冲区大小为 3 的 channel 和一个 goroutine,您可以写入 if 3 次而不从中读取。第 4 次写入将使所有 goroutine 进入休眠状态。

关于go - 为什么我们需要在 go routine 中运行无缓冲 channel ,而缓冲 channel 可以在没有 go routine 的情况下工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57860319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com