In the GO tutorial, we have this slide: Goroutines
package main import ( "fmt" "time" ) func say(s string) { for i := 0; i < 5; i++ { time.Sleep(100 * time.Millisecond) fmt.Println(s) } } func main() { go say("world") say("hello") }
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?
So in Go language, you are allowed to pause the execution of the current goroutine by using Sleep() function. This function pauses the current goroutine for at least the specified duration, after completing the specified duration the goroutine wakes up automatically and resume its working.
In Golang, Goroutines are used to achieve concurrency. They are lightweight threads managed by the Go runtime. Goroutines make it possible to create concurrent programs that can execute tasks faster than a regular sequential program would.
The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package.
In the case of goroutines, since stack size can grow dynamically, you can spawn 1000 goroutines without a problem. As a goroutine starts with 8KB (2KB since Go 1.4) of stack space, most of them generally don't grow bigger than that.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With