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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址