Why is time.sleep required to run certain goroutines?


In the GO tutorial, we have this slide: Goroutines

package main

import (

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)

func main() {
    go say("world")

Running this code produces expected results (“world” and “hello” written to the screen interchangeably 5 times).

However, if we comment out time.Sleep (and consequently, the "time" line of the import) and run the program again, we are left with only “hello” written to the screen five times.

What is so important about time.Sleep that saves the goroutine from dying?


If you remove the time.Sleep you don’t give the say("world") goroutine a chance to run. The goroutine scheduler is not preemptive. Your goroutines have to give up control before another goroutine will run. One way to give up control is to run time.Sleep.

If you take out the time.Sleep from the say function then the primary goroutine runs 5 times without giving up control to the secondary goroutine and then when the primary goroutine returns from say the program exits because there is nothing to keep the program alive.

Answered By – Daniel

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.