doucuo4413 2019-09-09 19:42
浏览 7

为什么我们需要在go例程中运行未缓冲的通道,但是缓冲通道无需go例程也可以工作?

I was going through tutorials on gobyexample. I noticed the author has shown example of gochannel using go routine but in buggered go channel he is directly sending messages to channel .

I tried on my local system to run unbuffered channel without go routine but it is throwing "fatal error: all goroutines are asleep - deadlock!" but buffered channels are working fine without 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)
}
  • 写回答

2条回答 默认 最新

  • dsa5233 2019-09-09 19:46
    关注

    A channel send will succeed only if the channel can accept the input, that is, either there's a listener for that channel, or there is available buffer in the channel. Otherwise goroutine will go to sleep until one of those become true: either someone starts listening, or someone reads from the channel and there is now buffer space.

    With a channel with no buffer, the only way you can write to it is if someone is listening to it. If there is only one goroutine and if you write to the channel, all goroutines will be asleep.

    With a channel with buffer size 3 and one goroutine, you can write to if 3 times without reading from it. The 4th write will put all goroutines to sleep.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度