dsd30433 2016-10-25 03:49
浏览 30
已采纳

需要了解goroutines [重复]

This question already has an answer here:

I am new to Go language programming and learning it step by step.
While practicing it, I found random behavior of goroutines.
If I call goroutine (function having sleep of 1 second), some times it completed successfully and some times it doesn't:

package main

import (
    "fmt"
    "time"
)

func t(i int) {
    fmt.Println("In func t")
    time.Sleep(1)
}

func t1(i int) {
    fmt.Println("In func t1")
    time.Sleep(1)
}

func main() {
    fmt.Println("Hello Good Morning")
    go t(1)
    t1(2)
    time.Sleep(5)
    fmt.Println("End of func main")
}

O/p 1 :

  Hello Good Morning
  In func t1
  In func t
  End of func main

O/p 2 :

  Hello Good Morning
  In func t1
  End of func main

Could someone explain why goroutine is not guaranteeing the execution of that goroutine function call.

</div>
  • 写回答

2条回答 默认 最新

  • douyin7829 2016-10-25 04:16
    关注

    Program execution:

    When the function main returns, the program exits. It does not wait for other (non-main) goroutines to complete.

    1- main is goroutine too, you need to wait for other goroutines to finish, and you may use

    time.Sleep(5 * time.Second)
    

    for 5 Seconds wait, try it on The Go Playground:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func t(i int) {
        fmt.Println("In func t")
        time.Sleep(1 * time.Second)
    }
    
    func t1(i int) {
        fmt.Println("In func t1")
        time.Sleep(1 * time.Second)
    }
    
    func main() {
        fmt.Println("Hello Good Morning")
        go t(1)
        t1(2)
        time.Sleep(5 * time.Second)
        fmt.Println("End of func main")
    }
    

    output:

    Hello Good Morning
    In func t1
    In func t
    End of func main
    

    And see Docs:

    // Sleep pauses the current goroutine for at least the duration d.
    // A negative or zero duration causes Sleep to return immediately.
    func Sleep(d Duration)
    

    2- You may use sync.WaitGroup to wait for other goroutines, try it on The Go Playground:

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    var w sync.WaitGroup
    
    func say(s string) {
        for i := 0; i < 2; i++ {
            time.Sleep(100 * time.Millisecond)
            fmt.Println(s)
        }
        w.Done()
    }
    
    func main() {
        w.Add(1)
        go say("A")
    
        w.Add(1)
        say("B")
    
        w.Wait()
    }
    

    output:

    B
    A
    A
    B
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集