why does it seem that sleep doesn't work in goroutine

Issue

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?

Solution

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)

Answered By – Joachim Isaksson

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.