Search code examples
goprometheus

Why is the code implemented like this ahout select in golang


for {
    select {
    case <-n.ctx.Done():
    return
    case ts := <-tsets:
    n.reload(ts)
    default:
        select {
    case <-n.ctx.Done():
        return
    case ts := <-tsets:
        n.reload(ts)
    case <-n.more:
        }
    }
}

the code above is in https://github.com/prometheus/prometheus/blob/main/notifier/notifier.go Function Run(tsets <-chan map[string][]*targetgroup.Group). Why default write select again, Dose it has any difference with the following code

for {
    select {
    case <-n.ctx.Done():
    return
    case ts := <-tsets:
    n.reload(ts)
    case <-n.more:
    }
}

I want to know the difference between these two implementation methods and their impact. thank u


Solution

  • This is a typical implementation of channel priority. If both <-tsets and <-n.more are available, the first code snipped gives priority to <-tsets. In fact, it will loop as long as <-tsets can be executed, and then it will start looking at <-n.more. Note that the only way the default case is selected is if <-tsets cannot run and context is not canceled. When that happens, it looks at <-n.more.