Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return at once in function when the context is cancel in GoLang?

package main

import (
    "context"
    "fmt"
    "time"
)

func main() {
    ctx := context.Background()
    c, fn := context.WithCancel(ctx)
    go doSth(c)
    time.Sleep(1 * time.Second)
    fn()
    time.Sleep(10 * time.Second)
}

func doSth(ctx context.Context) {
    fmt.Println("doing")
    time.Sleep(2 * time.Second)
    fmt.Println("still doing")
    select {
    case <-ctx.Done():
        fmt.Println("cancel")
        return
    }
}

OUTPUT:

doing
still doing
cancel

I don’t know how to make this doSth function return when the context it get is canncel.

In another word, I want the output of this function is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

OUTPUT:

doing
cancel

>Solution :

You can use a timer, which will send a message over a channel after the given duration. This allows you to add it in the select.

func main() {
    ctx := context.Background()
    c, fn := context.WithCancel(ctx)
    go doSth(c)
    time.Sleep(1 * time.Second)
    fn()
    time.Sleep(10 * time.Second)
}

func doSth(ctx context.Context) {
    fmt.Println("doing")
    timer := time.NewTimer(2 * time.Second)
    select {
    case <-timer.C:
        fmt.Println("still doing")
    case <-ctx.Done():
        fmt.Println("cancel")
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading