fatal error: all goroutines are asleep - deadlock! when channel is not buffered

前端 未结 1 1973
暖寄归人
暖寄归人 2021-01-29 05:55

I try to understand the error i got when channel is not buffered:

\"fatal error: all goroutines are asleep - deadlock!\"

pac         


        
1条回答
  •  清歌不尽
    2021-01-29 06:42

    Both sending and retrieving data through non-buffered channel are blocking processes.

    In your code you tried to send numeric value 1 through channel ch. Since the operation is blocking, the code underneath will not be executed before the current line execution is done.

    During execution of statement ch <- 1, in the same time no process running for retrieving data from the channel ch. Because the channel type is non buffered channel, the sending and retrieving process need to be happen in the exact same time.

    In example below I created a goroutine contains a code to send data through channel, and another code in the main routine to retrieve data from the channel. This will work since the main routine and goroutine process will be executed separately and concurrently.

    go func () {
        ch <- 1
    }()
    
    gg := <-ch 
    

    Working playground: https://play.golang.org/p/ceIoVQLItNk


    There is also something called buffered channel. Using this, you'll be able to send data through channel multiple times even though no process for retrieving the data is running at the same time, yet. But there is a rule to follow: you can only send it n times, while n represents the buffer number.

    Example 1: send data 2 times (buffer set to 3), then retrieve it:

    ch := make(chan int, 3)
    ch <- 1
    ch <- 1
    gg := <-ch
    

    Output: no panic

    Example 2: send data 4 times (buffer set to 3), then retrieve it:

    ch := make(chan int, 3)
    ch <- 1
    ch <- 1
    ch <- 1
    ch <- 1
    gg := <-ch
    

    Output: fatal error: all goroutines are asleep - deadlock!


    More information: https://blog.golang.org/pipelines

    0 讨论(0)
提交回复
热议问题