I am trying to run this below piece of code
package main
import (
"fmt"
"time"
)
func main() {
time.Sleep(time.Millisecond*6000)
fmt.Println("Done")
}
As one expects, it waits for 6 seconds, print "done" and then exits
But if I remove the print statement,
package main
import (
"time"
)
func main() {
time.Sleep(time.Millisecond*6000)
}
it doesn't wait and exits immediately. Why?
Consequently, look at the code below
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
go count(6, c)
time.Sleep(time.Millisecond*5000)
}
func count(num int, c chan int) {
for i := 1; i <= num; i++ {
fmt.Println(i)
c <- i
time.Sleep(time.Millisecond*2000)
}
close(c)
}
Here the count
goroutine will get blocked trying to send i
to a channel when no receiver is there to read it and the main
function immediately exits even though there is a sleep
statement after it. But when I remove the statement
c <- i
the count
goroutine gets to count till 3 since the main
function does wait for those 5 seconds as stated.
What is going on here?