简体   繁体   中英

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

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

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

package main

import "fmt"

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

it works after I buffer the channel ch := make(chan int, 2)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM