英文:
why does it seem that sleep doesn't work in goroutine
问题
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan struct{})
count := 1
go func() {
for {
fmt.Println("foo", count)
count++
time.Sleep(2 * time.Second) // 修改这里的时间间隔为2秒
}
c <- struct{}{}
}()
fmt.Println("Hello World!")
<-c
}
这是你的代码,我发现它没有在每次循环中休眠2秒,而是快速打印。原因是什么?根据我的搜索,休眠会使goroutine放弃对CPU的控制,当它再次获得控制权时,它会检查自己是否正在休眠。
问题可能出在你的代码中的time.Sleep(2)
这一行。time.Sleep
函数的参数是纳秒级别的,所以你需要将参数修改为time.Sleep(2 * time.Second)
,这样才能实现2秒的休眠。
修改后的代码会在每次循环中休眠2秒,确保打印间隔为2秒。
英文:
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan struct{})
count := 1
go func() {
for {
fmt.Println("foo", count)
count++
time.Sleep(2)
}
c <- struct{}{}
}()
fmt.Println("Hello World!")
<-c
}
This is my code , and I found it didn't sleep 2 every loop, and printed quickly. What's the reason of it? What I searched is that sleep will make goroutine give up control of cpu and when it get the control again will it check itself is sleeping?
答案1
得分: 10
time.Sleep 函数接受以纳秒为单位的 Duration 参数,所以要延迟2秒,可以这样写:
time.Sleep(2000000000)
或者,如评论中 @Ainar-G 指出的那样,更易读的写法是:
time.Sleep(2 * time.Second)
英文:
time.Sleep takes its Duration in nanoseconds, so to delay 2 seconds it should be;
time.Sleep(2000000000)
or, as @Ainar-G points out in the comments, the more readable;
time.Sleep(2 * time.Second)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论