0

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
}
1
  • There is no single answer. It depends on how you want the API to work. In some cases, you may even do both. For example. http.ListenAndServe blocks (doesn't start a goroutine to run in the background), but it creates a goroutine for each request. Dec 27, 2020 at 13:07

1 Answer 1

1

In Go it's trivial to launch a function as a goroutine (with the go keyword / statement), so always leave that option to the caller whether he/she wants to run your function synchronously or asynchronously.

That way you also relive yourself from delivering the result asynchronously, the client might already have a designated channel for that, "integrated" into other goroutines waiting for the result to process. Similarly, the client might already have a started goroutine preparing other things, and so the client can utilize that goroutine without having to launch another one if you "wire" that in.

Not the answer you're looking for? Browse other questions tagged or ask your own question.