为什么在Go协程中使用time.Sleep(2)无效?

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

Why doesn't time.Sleep(2) work with go routines?

问题

从这里的go例子中:https://gobyexample.com/goroutines,为什么用time.Sleep(2)替换fmt.Scanln的代码不起作用?

如果你用time.Sleep(2)替换最后三行代码,go例程将不会打印任何内容。

func main() {
    f("direct")
    go f("goroutine")
    go func(msg string) {
        fmt.Println(msg)
    }("going")

    time.Sleep(2)
}
英文:

From the go routine example here: https://gobyexample.com/goroutines, why doesn't replacing the fmt.Scanln code with a time.sleep(2) work?

If you replace the last three lines with time.Sleep(2), the go routines don't print anything.

func main() {
	f("direct")
	go f("goroutine")
	go func(msg string) {
		fmt.Println(msg)
	}("going")

	time.Sleep(2)
}

答案1

得分: 4

time.Sleep 函数接受一个 time.Duration 类型的参数,单位为纳秒。如果你想要秒数,可以使用 time.Sleep(2*time.Second)

f("direct")
go f("goroutine")
go func(msg string) {
	fmt.Println(msg)
}("going")

time.Sleep(2 * time.Second)

Playground: http://play.golang.org/p/lgKSyAW4RO.

但是最好使用通道或 sync 包中的工具进行同步。

英文:

time.Sleep takes time.Duration as an argument, which is in nanoseconds. If you want seconds, use time.Sleep(2*time.Second):

f("direct")
go f("goroutine")
go func(msg string) {
	fmt.Println(msg)
}("going")

time.Sleep(2 * time.Second)

Playground: http://play.golang.org/p/lgKSyAW4RO.

But it's always better to use channels or tools from package sync for synchronisation.

huangapple
  • 本文由 发表于 2015年10月29日 22:07:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/33416475.html
匿名

发表评论

匿名网友

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

确定