If I define a channel without buffer and write one data into it, does it block immediately(so that the kernel will look for another unblocked goroutine that reads from the channel), or does it continues execution and blocks when the next time some code tries to write into the channel again, when it hasn't been read yet?
Below are two pieces of codes I wrote to research on this problem.
code1:
package main
import "fmt"
func main() {
c := make(chan int)
go func() {
for i := 0;i < 3; i++ {
c <- i
fmt.Printf("number %v inserted into channel
", i)
}
}()
for i := 0; i < 3; i++ {
fmt.Printf("number poped from channel %v
", <-c)
}
}
The output is like this:
number 0 inserted into channel
number poped from channel 0
number poped from channel 1
number 1 inserted into channel
number 2 inserted into channel
number poped from channel 2
After the first time c is written into, this goroutine seems to continue to be executed, since "number 0 inserted into channel" was printed.
code2:
package main
import "fmt"
func main() {
c := make(chan int)
c <- 2
fmt.Println("Something is written into channel")
<-c
}
This piece of code cannot run correctly since a deadlock error is reported at runtime.
fatal error: all goroutines are asleep - deadlock!
From my view, when c <-2 is executed, the goroutine is blocked(if it's not blocked, the fmt.Println line will be executed and continuing executing will unlock c at <-c). When this goroutine is blocked, the kernel searches other goroutines and find none, so it reports a deadlock error.
In summary, in the first piece of code I conclude that writting to a channel doesn't block the goroutine immediately but from the second piece of code it does. Where did I get it wrong and when does a channel blocks a goroutine?