Assume that you have multiple job channels and you want to process jobs in a specific channel first because they are more important. In example below we are concurrently placing jobs into both channels. Important jobs go into urgentJobs channel and non-important ones go into trivialJobs channel. As long as there is a job in urgentJobs channel, the listener processes it first otherwise it falls back to trivialJobs channel so technically the jobs in trivialJobs channel tend to wait.


Example


package main

import (
"fmt"
"time"
)

func main() {
urgentJobs := make(chan int)
trivialJobs := make(chan int)

go listener(urgentJobs, trivialJobs)

go func() {
for i := 1; i <= 10; i++ {
trivialJobs<- i
}
}()
go func() {
for i := 1; i <= 10; i++ {
urgentJobs<- i
}
}()
go func() {
for i := 1; i <= 10; i++ {
urgentJobs<- i
}
}()

time.Sleep(5*time.Second)
}

func listener(urgentJobs <-chan int, trivialJobs <-chan int) {
for {
select {
case job := <-urgentJobs:
urgent(job)
default:
select {
case job := <-urgentJobs:
urgent(job)
case job := <-trivialJobs:
trivial(job)
}
}
}
}

func urgent(job int) {
fmt.Println("URG:", job)
}

func trivial(job int) {
fmt.Println("TRV:", job)
}

Test


TRV: 1
TRV: 2
URG: 1 *
URG: 1 *
URG: 2 *
URG: 2 *
URG: 3 *
URG: 3 *
URG: 4 *
URG: 4 *
URG: 5 *
URG: 5 *
URG: 6 *
URG: 6 *
URG: 7 *
URG: 7 *
URG: 8 *
URG: 8 *
URG: 9 *
URG: 9 *
URG: 10 *
URG: 10 *
TRV: 3
TRV: 4
TRV: 5
TRV: 6
TRV: 7
TRV: 8
TRV: 9
TRV: 10