Channel &buffered channel

package main

import “fmt”

func main() {
c := make(chan int)//
c <- 1 //write
v:=<-c //read
c <- 2 //write again
fmt.Println(<-c) //read again
} while this code can’t run successfully with error:fatal error: all goroutines are asleep - deadlock!

I know c is blocking .but i read after wrote and I didn’t get the explanation that convincing

Your channel is not buffered. When you send to it (c <- 1) the send can only proceed if there is another routine receiving from it. There is not, so the write blocks. There are no other goroutines running, so every goroutine is blocked (or asleep) - this is a deadlock and the program crashes.

1 Like

thanks a lot. it seems that :for a channel not buffered.the write and read must from different goroutines. am i right?


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.