Why is time.sleep required to run certain goroutines?

前端 未结 3 639
夕颜
夕颜 2020-12-13 18:54

In the GO tutorial, we have this slide: Goroutines

package main

import (
    \"fmt\"
    \"time\"
)

func say(s string) {
    for i := 0; i < 5; i++ {
           


        
3条回答
  •  盖世英雄少女心
    2020-12-13 19:32

    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

提交回复
热议问题