gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:47 25 4
gpt4 key购买 nike

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

package main

import (
"fmt"
"time"
)

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

正如预期的那样,它等待 6 秒,打印“完成”然后退出

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

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 到一个 channel ,当没有接收者在那里读取它和 main 函数立即退出,即使它后面有一个 sleep 语句。但是当我删除语句时

c <- i

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

这是怎么回事?

最佳答案

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

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

关于go - 如果没有进一步的语句要执行,为什么 time.Sleep 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58079847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com