Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

GO channel deadlock if channel is created with package scope

I am go newbie and trying to understand channels. Why does following go snippet deadlocks(fatal error: all goroutines are asleep – deadlock!) even though there are two routines working with given channel?

package main

import "fmt"

var helloChan chan int

func main() {
    fmt.Printf("%T\n", helloChan)
    go func() {
        helloChan <- 42
    }()
    fmt.Println("got from chan: ", <-helloChan)
}

Following works and there is no additional goroutine. Only difference is how channel is created. The type is same in both case though.

package main

import "fmt"

func main() {
    helloChan := make(chan int)
    fmt.Printf("%T\n", helloChan)
    go func() {
        helloChan <- 22
    }()
    fmt.Println("got from chan: ", <-helloChan)
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the first example you never created the channel, the helloChan variable is nil. If you update it to create the channel it’ll work the same as the second one.

package main

import "fmt"

var helloChan chan int

func main() {
    helloChan = make(chan int)
    fmt.Printf("%T\n", helloChan)
    go func() {
        helloChan <- 42
    }()
    fmt.Println("got from chan: ", <-helloChan)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading