Skip to content

Instantly share code, notes, and snippets.

@robbiev robbiev/priority_select.go
Last active Nov 26, 2019

Embed
What would you like to do?
select with priority in go
// SOLUTION 1
// see https://groups.google.com/forum/#!topic/golang-nuts/ChPxr_h8kUM
func maybe(b bool, c chan int) chan int {
if !b {
return nil
}
return c
}
select {
case <-maybe(val>0, p):
val--
case <-v:
val++
}
// SOLUTION 2
// see https://groups.google.com/forum/#!topic/golang-nuts/M2xjN_yWBiQ
select {
case <-higher:
foo()
default:
select {
case <-lower:
bar()
default:
...
}
}
@Kent-H

This comment has been minimized.

Copy link

Kent-H commented Nov 26, 2019

If default is not defined on the innermost select, it should include all previous cases, like:

select  {
case <-higher:
        foo()
default:
        ...
        select {
        case <-higher:
                foo()
        case <-lower:
                bar()
        ...
        }
}

Thus higher is prioritized, but any channel can trigger execution if none are ready initially.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.