英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论