Why this function can not exit?

Issue

I try to run the main function but it can not end. I don’t know why.

func main() {
    tick := time.Tick(1 * time.Second)
    done := make(chan bool)
    go func() {
        for {
            select {
            case <-tick:
                println("-------hah---------")
            case <-time.After(2 * time.Second):
                println("after 1 second.")
                done <- true
            }
        }
    }()
    <-done
}

I expect the function can exit successfully, but the function can not end

Solution

Your select statement has two options:

        case <-tick:

which triggers every 1 second, and

        case <-time.After(2 * time.Second):

which triggers 2 seconds after starting the select loop.

Since your first case always happens after 1 second, the second case will never occur. And it is only the second case which triggers exiting the main function.

What you probably intended was instead this:

tick := time.Tick(1 * time.Second)
timer := time.After(2 * time.Second)

and

case <-timer:

Answered By – Flimzy

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.