duanmaifu3428 2017-10-09 12:01
浏览 55
已采纳

基本的Golang流(通道)死锁

I am trying to work with go streams and I have a few "stupid" question.

I have done a primitive stream example with the byte limit range and here is the working code and here are my questions.

1 - why this code shows 1 and 2 at the new line? Why doesn't it show 12 at the one? Does the first peace of bytes removed from the byte-limited stream? (But how we can push the 2 number into the stream when we have already pushed the 1 number?) I just can't understand it

package main

import "fmt"

func main() {
    ch := make(chan int, 2)
    ch <- 1
    ch <- 2
    fmt.Println(<-ch)
    fmt.Println(<-ch)
}
It shows:
1
2

2 question - I have tried to play with this code to understand how it works and I have removed the byte range and I have got the deadlock error. Why does it happen? Thanks!

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
    /tmp/sandbox557775903/main.go:7 +0x60

The deadlock error code:

package main

import "fmt"

func main() {
    ch := make(chan int)
    ch <- 1
    ch <- 2
    fmt.Println(<-ch)
    fmt.Println(<-ch)
}

Thanks for any help! Sorry for the primitive questions.

  • 写回答

2条回答 默认 最新

  • dongzhi6146 2017-10-09 18:51
    关注

    Because channel operator <- takes only 1 element from the channel. If you want them printed together try: fmt.Println("%v%v", <-c, <-c)"

    Last number in channel creation make(chan int, 2) means channel buffer - its capacity to store items. So you can easily push 2 items to channel. But what happens if you try to push one more item? The operation would be blocked because there's no space until another goroutine will read from the channel and free space.

    The same applies to all channels - unbuffeted ones get blocked at first element writing. Until some goroutine reads from the channel.

    Because there's no goroutine to read, writing one locks forever. You may solve it starting a reading goroutine before.

     c := make(chan int)
    go func () {
        fmt.Println(<-c)
        fmt.Println(<-c)
    }()
    ch <- 1
    ch <- 2
    

    This way would not get locked but start transmitting items.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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