GoLang program waiting instead of panicking with “all goroutines are asleep – deadlock”

  Kiến thức lập trình

When I run Program 1 with command go run main.go it terminates with error all goroutines are asleep - deadlock! while the Program 2 keep waiting and does not terminate. We are not calling checkLink function and still we are seeing different behaviour. Can you please explain this?

Also when I ran the executable file which is output of go build main.go for Program 2, It was killed and executable file deleted.

Program 1

package main

import (
    "fmt"
)

func main() {
    c := make(chan int)
    c <- 4
    x := <-c
    fmt.Println(x)
}

Program 2

package main

import (
    "fmt"
    "net/http"
)

func main() {
    c := make(chan int)
    c <- 4
    x := <-c
    fmt.Println(x)
}

func checkLink(link string, c chan string) {
    fmt.Println("checking", link)
    _, err := http.Get(link)
    if err != nil {
        c <- link + " is down"
        return
    }
    c <- link + " is up"
}

NOTE : I am running this on MacOs and shell is ZSH

New contributor

Sandeep Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT