dongsashe6006 2015-10-29 14:07
浏览 93
已采纳

为什么time.Sleep(2)不使用go例程?

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条回答 默认 最新

  • dongyuan8469 2015-10-29 14:18
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?