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
Edit The behaviour of Program 2 is the same as that of Program 1 when I run it in Go Tour.
http.Get
call is usually going to result in a network connection with read/write goroutines. The case thatCerise Limón
mentioned of just importing thenet
package, that is the result of the internal infrastructure to trampoline name resolution to the host resolver via cgo. Building without that via thenetgo
tag will avoid the behavior. – Urania