dtvjl64442 2018-02-08 16:02
浏览 99
已采纳

在繁忙的程序中进入goroutine睡眠

I have a switch statement inside a goroutine which handles the playback state of audio. The switch statement looks like this (it's controlled with channels)

PlaybackLoop:
        // Poll playback status and update current song
        select {
        case <-next:
            if current.next != nil {
                current = current.next
                break PlaybackLoop
            }
        case <-prev:
            if current.prev != nil {
                current = current.prev
            }
            break PlaybackLoop
        case <-done:
            return err
        default:
            time.Sleep(50 * time.Millisecond)

When no channels have inputs, the default case sleeps for 50 milliseconds. My justification for this is that I do not to refresh the UI or check media state etc (the stuff that happens in the PlayBackLoop before the switch statement) unnecessarily.

Is sleeping and appropriate way of making the goroutine more efficient? (by making less checks to the media player state?) Or is this assumptions wholly unfounded, and a simple continue would suffice?

  • 写回答

1条回答 默认 最新

  • doushi1847 2018-02-08 17:55
    关注

    Using calls to time.Sleep is never the right option for coordination of concurrent processes, and it is better to rely on synchronization primitives and the runtime to coordinate the concurrency whenever possible.

    In this case it appears that you are polling for an event, and the sleep is there to prevent you from running a busy loop, which would only waste cpu and possibly starve other goroutines/threads of CPU.

    If you cannot avoid the need to poll for an event, then you can improve this slightly by using a time.Ticker to make the polling interval more consistent.

        ticker := time.NewTicker(pollInterval)
        defer ticker.Stop()
    
    PlaybackLoop:
        for {
            select {
            case <-next:
                if current.next != nil {
                    current = current.next
                    break PlaybackLoop
                }
            case <-prev:
                if current.prev != nil {
                    current = current.prev
                }
                break PlaybackLoop
            case <-done:
                return err
            case <-ticker.C:
                pollForEvent()
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?