No output from goroutine

后端 未结 3 630
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 06:21

While SayHello() executes as expected, the goroutine prints nothing.

package main

import \"fmt\"

func SayHello() {
    for i := 0; i < 10          


        
3条回答
  •  隐瞒了意图╮
    2020-11-22 06:57

    Alternatively (to icza's answer) you can use WaitGroup from sync package and anonymous function to avoid altering original SayHello.

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func SayHello() {
        for i := 0; i < 10; i++ {
            fmt.Print(i, " ")
        }
    }
    
    func main() {
        SayHello()
    
        var wg sync.WaitGroup
        wg.Add(1)
    
        go func() {
            defer wg.Done()
            SayHello()
        }()
    
        wg.Wait()
    }
    

    In order to print numbers simultaneously run each print statement in separate routine like the following

    package main
    
    import (
        "fmt"
        "math/rand"
        "sync"
        "time"
    )
    
    func main() {
        var wg sync.WaitGroup
    
        for i := 0; i < 10; i++ {
            wg.Add(1)
            go func(fnScopeI int) {
                defer wg.Done()
    
                // next two strings are here just to show routines work simultaneously
                amt := time.Duration(rand.Intn(250))
                time.Sleep(time.Millisecond * amt)
    
                fmt.Print(fnScopeI, " ")
            }(i)
        }
    
        wg.Wait()
    }
    

提交回复
热议问题