go - channel 缓冲区在没有 goroutines 的情况下(在其范围内)与传递给 goroutines 时如何在 golang 中工作?

标签 go goroutine

我绝对是 Golang 的新手。我正在通过 Tour of Go 学习,然后用我自己的理解来实现想法。我在使用 goroutines 时遇到问题。我创建了一个无缓冲 channel ,然后向该 channel 发送了一个字符串。

func main() {
    p := make(chan string)
    p <- "Hello goroutine"
    fmt.Println(<-p)
}

抛出错误

fatal error: all goroutines are asleep - deadlock!

我明白了, channel 是无缓冲的。 (就是这个原因。对吧?)。

但是当我重构 p <- "Hello goroutine到协程

func main() {
    p := make(chan string)
    go sendHello(p)
    fmt.Println(<-p)
}

func sendHello(p chan string) {
    p <- "Hello goroutine"
}

它工作没有问题。我读到在大多数情况下我们不需要使用带有映射、 slice 和 channel 的指针来修改值。 channel p传递给 func sendHello(p chan string)通过具有单独缓冲区的副本。我仍然无法理解它。

最佳答案

请记住, channel 有两个端点,一个是发送者,一个是接收者。您的问题与执行顺序有关。

在第一个示例中,当您使用无缓冲 channel 时,该 channel 需要一个接收器,而没有发送Hello goroutine 消息,并等待直到有一个(缓冲 channel 不是这种情况,因为它不需要等待),并且执行永远不会到达下一行(即死锁)。

但是在第二个例子中,receiver 绑定(bind)到 channel 之后执行 groutine,senderreceiver 都没有保持等待状态.

关于go - channel 缓冲区在没有 goroutines 的情况下(在其范围内)与传递给 goroutines 时如何在 golang 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53814981/

相关文章:

multithreading - Go 运行时使用的线程数

go - 为什么我的 for 循环不能正确循环元素?

excel - 如何计算Excel日期生成的自1900年以来的天数?

arrays - 如何使用go从mongoDB数组中获取所有元素?

multithreading - 在 Go 中关闭自馈 channel

go - 如何在运行例程时将值分配给结构?

go - 带有嵌套负载的 JSON 绑定(bind)

go - SQLBoiler 从 `AndIn` 中的另一个表中选择

amazon-web-services - Go 代理到 S3 文件适用于本地主机但不适用于生产

go - 为什么 goroutine 的竞争条件不会在某个时候发生?