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 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答