Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
package main
import "fmt"
func main() {
ch := make(chan int)
ch <- 1
fmt.Println(<-ch)
}Runtime error: all goroutines are asleep (deadlock)
- Expecting
1: an unbuffered channel stores nothing, soch <- 1waits for a receiver, and the receive on the next line never starts. - Expecting a silent hang: the runtime sees that every goroutine is blocked and stops the program with
fatal error: all goroutines are asleep - deadlock!.
- How would
make(chan int, 1)change the outcome? - How else can the program print
1while keeping the channel unbuffered?