In the GO tutorial, we have this slide: Goroutines
package main
import (
\"fmt\"
\"time\"
)
func say(s string) {
for i := 0; i < 5; i++ {
If you remove time.Sleep from the say function the main will execute say("hello") and terminate without executing the goroutine. If you add a time.Sleep (or otherwise a select {}) before the main end it will give time to the goroutine to run and that thread will be picked from the scheduler.
Example:
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")
time.Sleep(1*time.Second)
// Vs:
// select {} // blocks indefinitely, requires manual interrupt
// In CSP-speak the empty select is like STOP.
// for{} would cause the cpu to max and the process's STATE will be `running`
// select{} will not cause the cpu to max and the process state will be `sleeping`
}
The output will usually be 5 hello followed by 5 world but it could also manage to print one of the world before the last hello
TRY IT --> (http://) goo.gl/K2v7H0