普通网友 2018-12-17 12:10
浏览 43
已采纳

在不使用goroutines(在其作用域内)和将其传递给goroutines时,通道缓冲区如何在golang中工作?

I am absolute newbie in Golang. I am learning through Tour of Go and then implementing ideas with my own understanding. I am having problem with goroutines. I made a unbuffered channel , then sent a string to that channel.

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

throws error

fatal error: all goroutines are asleep - deadlock!

I get it, channel is unbuffered. (That's the reason. Right?).

But when I refactor p <- "Hello goroutine to a goroutine

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

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

It works without problem. I read that we do not need to use pointers with maps,slices and channels with most cases to modify the value. Was channel p passed to func sendHello(p chan string) via a copy which had a separate buffer. I still can not get my head around it.

  • 写回答

1条回答 默认 最新

  • douyan1453 2018-12-17 12:27
    关注

    Keep in mind that a channel has two ends, a sender and a receiver. Your problem is about the order of execution.

    In the first example, when you use an unbuffered channel, the channel expects a receiver, while there's none as of sending Hello goroutine message, and waits until there's one (this is not the case for a buffered channel as it doesn't require to wait), and the execution never reaches the next line (i.e. a deadlock).

    But in the second example, the receiver is bound to the channel and the groutine is executed after, and both sender and receiver don't remain in a wait state.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看