如果没有进一步的语句要执行,为什么 time.Sleep 不起作用?

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

我正在尝试 运行 下面这段代码

package main

import (
    "fmt"
    "time"
)

func main() {
    time.Sleep(time.Millisecond*6000)
    fmt.Println("Done")
}

不出所料,等待6秒,打印"done"然后退出

但是如果我删除打印语句,

package main

import (
    "time"
)

func main() {
    time.Sleep(time.Millisecond*6000)
}

它不等待并立即退出。为什么?

因此,请看下面的代码

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)
}

这里 count goroutine 将被阻止尝试发送 i 到一个通道,当没有接收者在那里读取它并且 main 函数立即退出,即使有一个sleep 声明在它之后。但是当我删除声明时

c <- i

count goroutine 计数到 3,因为 main 函数确实按照规定等待那 5 秒。

这是怎么回事?

运行 它在本地,它会等待。 Go Playground 上的输出被缓存。如果没有输出,也不会让你白等6秒。如果有输出,则保留输出的时序。

阅读博客 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.