简体   繁体   中英

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. 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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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