doumao1047 2019-05-07 20:27
浏览 99
已采纳

如何确保所有goroutine都没有time.Sleep终止? [重复]

I'm trying to experiment with go routines about who gets the message first. However, when the main goroutine terminates, some go routines are still hanging around. I see this through the stack trace from panic. However, If I add time.Sleep they all terminate. I guess this is because, when the main go routines ends, Go runtime couldn't find time to terminate the others.

    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        for i := 0; i < 1000000; i++ {
            algo()
        }

        // without this, some goroutines do not terminate
        // time.Sleep(time.Second)

        panic("")
    }

    func algo() {
        c := make(chan int)
        wait := make(chan bool)

        go racer(1, wait, c)
        go racer(2, wait, c)
        go racer(3, wait, c)
        go racer(4, wait, c)
        go racer(5, wait, c)

        // who gets it first
        c <- 5
        close(wait)
    }

    func racer(name int, wait chan bool, c chan int) {
        select {
        case <-wait:
        case v := <-c:
            fmt.Println(name, ":", v)
        }
    }
</div>
  • 写回答

1条回答 默认 最新

  • doupai8095 2019-05-07 20:30
    关注

    That's exactly what sync.WaitGroup is for. Here's a toy example taken from this blog post:

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    func main() {
        messages := make(chan int)
        var wg sync.WaitGroup
    
        // you can also add these one at 
        // a time if you need to 
    
        wg.Add(3)
        go func() {
            defer wg.Done()
            time.Sleep(time.Second * 3)
            messages <- 1
        }()
        go func() {
            defer wg.Done()
            time.Sleep(time.Second * 2)
            messages <- 2
        }() 
        go func() {
            defer wg.Done()
            time.Sleep(time.Second * 1)
            messages <- 3
        }()
        go func() {
            for i := range messages {
                fmt.Println(i)
            }
        }()
    
        wg.Wait()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog