dimanche 27 décembre 2020

Goroutine creation design pattern

When writing logic that should be run as part of a goroutine, should the method itself create the goroutine or the should that be the responsibility of the calling function? For example, which of the below would be preferable?

Creating the go routine within the method

func longrunning() chan Result {
    c := make(chan Result)
    go func() {
        // Business Logic Here
        c <- Result{}
    }()
    return c
}

func main() {
    c := longrunning()
    
    // Do additional tasks
    
    <-c
}

Leaving it up to the caller

func longrunning() Result {
    // Business Logic Here
    return Result{}
}

func main() {
    c := make(chan Result)

    go func() {
        c <- longrunning()
    }()
    
    // Do additional tasks

    <-c
}

Aucun commentaire:

Enregistrer un commentaire