Search code examples
gotimegoroutinechannelgo-playground

Why does time.Sleep not work if there are no further statements to execute?


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?


Solution

  • Run it locally, and it will wait. The output on the Go Playground is cached. If there is no output, it doesn't make you wait 6 seconds for nothing. If there is output, the timing of the output is preserved.

    Read blog post: The Go Blog: Inside the Go Playground:

    We capture the timing of each write to standard output and standard error and provide it to the client. Then the client can "play back" the writes with the correct timing, so that the output appears just as if the program were running locally.