为什么在goroutine中似乎无法使用睡眠(sleep)函数?

huangapple go评论85阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;time&quot;
)

func main() {
	c := make(chan struct{})
	count := 1
	go func() {
		for {
			fmt.Println(&quot;foo&quot;, count)
			count++
			time.Sleep(2)
		}
		c &lt;- struct{}{}
	}()
	fmt.Println(&quot;Hello World!&quot;)
	&lt;-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)

huangapple
  • 本文由 发表于 2014年7月22日 21:57:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/24889431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定