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


package main

import (

func main() {
    c := make(chan struct{})
    count := 1
    go func() {
        for {
            fmt.Println("foo", count)
        c <- struct{}{}
    fmt.Println("Hello World!")

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;


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.