Why all goroutines are asleep when using select and sequentially feeding values into 2 channels?

Issue

I have 2 channels which I pass values to at the start of main function and then I have an anonymous goroutine which should print the values:

package main

import (
    "fmt"
)

func main() {
    rand1 := make(chan int)
    rand2 := make(chan int)
    rand1 <- 5
    rand2 <- 7

    go func() {
        select {
        case <-rand1:
            fmt.Println("rand1")
        case <-rand2:
            fmt.Println("rand2")
            return
        }
        fmt.Println("test")
    }()
}

However I receive the error fatal error: all goroutines are asleep - deadlock!. But the anonymous goroutine is supposed to return when rand2 channel is receives its value.

Solution

The write to a channel will block until another goroutine reads from it. Your program is trying to write to a channel before you start the reader goroutine. Start the reader goroutine first, and then write to the channels.

Not that the way it is written, the goroutine will only read from one of the channels and return, so your program will deadlock again because the second write will block.

Answered By – Burak Serdar

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.