简体   繁体   English

为什么睡眠在goroutine中不起作用

[英]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)
        }
        c <- struct{}{}
    }()
    fmt.Println("Hello World!")
    <-c
}

This is my code , and I found it didn't sleep 2 every loop, and printed quickly. 这是我的代码,我发现它每个循环都没有休眠2次,并迅速打印。 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? 我搜索的是睡眠将使goroutine放弃对cpu的控制,当再次获得控制时,它将检查自身是否正在睡眠?

time.Sleep takes its Duration in nanoseconds, so to delay 2 seconds it should be; time.Sleep持续时间以纳秒为单位,因此应延迟2秒;

time.Sleep(2000000000)    

or, as @Ainar-G points out in the comments, the more readable; 或者,正如@ Ainar-G在评论中指出的那样,可读性更好;

time.Sleep(2 * time.Second)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM