Out of 3 code snippets, the one with channels declared in local scope works, other code snippets gives deadlock issue, One of the previously answered SO question here says try to avoid declaring channel in the global scope. I checked in the official docs, but I didn't find any explanation.
Why is the global scope channel giving an error although I am not blocking the channel from sending and receiving? why am I getting a deadlock issue here?
How is
make(chan int)
different fromvar myChan chan int
except in terms of scope and initialization?Can anyone explain and suggest better articles/documents/links/pdfs to effectively use channels(and implement concurrency) in Go?
(imports and 'package main' is omitted from snippets for purpose of brevity)
// 1. channel declared in global scope
var c chan int
func main(){
go send()
fmt.Println(<-c)
}
func send(){
c <- 42
}
//output: fatal error: all goroutines are asleep - deadlock!
// 2. channel declared in global scope + sending channel to goroutine
var c chan int
func main(){
go send(c)
fmt.Println(<-c)
}
func send(c chan int){
c <- 42
}
//output: fatal error: all goroutines are asleep - deadlock!
// 3. using channel as local scope and sharing it with goroutine
func main(){
c := make(chan int)
go send(c)
fmt.Println(<-c)
}
func send(c chan int){
c <- 42
}