Thursday, January 3, 2019

Go select{} by priority

Here's a weird pattern for doing Go select statements and achieving doing the highest priority thing first.


for {
    select { // A is the highest priority, if available, do that
    case <-A:
        continue
    default: // don't block here
    }

    select { // A and B are high priority, if available, do one
    case <-A:
        continue
    case <-B:
        continue
    default: // don't block here
    }

    select { // Nothing high priority being available, wait for whatever is available next and do that.
    case <-A:
        continue
    case <-B:
        continue
    case <-C:
        continue
    }
}

Note that every case ends with `continue` so as to go back to the top and re-evaluate all the priority decisions.
So, what do you think? Useful pattern? Horrible anti-pattern?

No comments: