Double checking <-ctx.Done()

40 views Asked by At

Assume the following snippet:

for {
    select {
    case val := <-chan:
        doSomething(ctx, val)
    case <-ctx.Done():
        return
    }
}

There could be a scenario where the context was canceled, but the select case still chooses the first case if the channel has messages in it. Resulting in calling doSomething with a canceled context.

A solution could be:

for {
    select {
    case val := <-chan:
        select {
        case <-ctx.Done():
            return
        default:
            doSomething(ctx, val)
        }
    case <-ctx.Done():
        return
    }
}

This would work, but it feels wrong.

Is there another cleaner way to achieve the same behavior?

0

There are 0 answers