Anup
Anup

Reputation: 1712

Cancel further operations on context cancellation

I have a func that receives context and does some cpubound operations like bellow.

func DoSomeOperation(ctx context.Context){
    CPUBoundWork1()
    CPUBoundWork2()
    CPUBoundWork3()
    CPUBoundWork4()
}

What I want to do is to check if Context has been cancelled or not before making each CPUBound func call. If cancelled I want to return immidiately without making next func call. Is there any way to do this?

Upvotes: 0

Views: 217

Answers (1)

kozmo
kozmo

Reputation: 4491

Use ctx.Err()

if ctx.Err() == context.Canceled {
    return
}

You also can use select statement with slice of functions.

For Example:

    ctx := ...
    executors := []func(){...}
Loop:
    for _,executor := range executors{
        select {
        case <-ctx.Done():
            if ctx.Err() == context.Canceled {
                break Loop
            }
            if ctx.Err() == context.DeadlineExceeded {
                //do something else
            }
        default:
            executor()
        }
    }

PLAYGROUND

Upvotes: 2

Related Questions