Sleep in goroutine with busy loop

Issue

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?

Solution

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()
        }
    }

Answered By – JimB

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.