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 maccms影视模板 制作影视网站失败 求
  • ¥15 stm32按键设置闹钟数进退位不正常
  • ¥15 三电平逆变器中点电位平衡问题
  • ¥20 这怎么写啊 java课设
  • ¥15 用C语言完成一个复杂的游戏
  • ¥15 如何批量更改很多个文件夹里的文件名中包含文件夹名?
  • ¥50 MTK手机模拟HID鼠标出现卡顿
  • ¥20 求下下面这个数据结构代码
  • ¥20 前端 二进制文件流图片转化异常
  • ¥15 github上的这个C语言项目如何跑起来